Blog for web designers

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";

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  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.

Santosh Shah

My name is Santosh Shah and blogs at santosh-shah.com


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.