Easy angular trick to disable and enable button while input box empty or populate

In this another small article I will show you how you simply enable and disabled the input button while you type. To perform this simple trick we will hide the button, if the input box is empty similarly if the input box is filled with any keyword the button will not be disabled.

To disabled it means the user will not be able to click the button. Now lets jump towards the button and let us see how the angular is going to perform the same.

In your app.component.html or any component you would like to try add the below code.

<input type="text" class="form-control" [(ngModel)]="dynamic_content">
<button class="btn btn-primary" [disabled]="dynamic_content=== ''">Save</button>

You may see the above code there are only two lines. Usually, there are 4 different types of data binding but in the code, we are using two types of data binding.

  • Two-way data binding and
  • One way data binding (here we are using ” Property data binding”)

Also note, in order to use ngModel inside the input element we need to import FormsModule from angular in app.module.ts file

import "FormsModule" from "@angular/forms";

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]

So whenever user type something in the input box, the data gets updated to the button’s property binding called [disabled]=”dynamic_content == ” “. So the disabled attribute checks if the dynamic_content variable is empty or filled with text. So it disabled the button if the variable is empty.

Leave a Reply

Your email address will not be published. Required fields are marked *