Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable button when input is empty in Angular 2

Tags:

angular

I want to check whether the input is empty.

  • If not empty, enable the submit button.
  • If empty, disable the submit button.

I tried (oninput) and (onchange), but they do not run.

<input type="password" [(ngModel)]="myPassword" (oninput)="checkPasswordEmpty()"/>

checkPasswordEmpty() {
    console.log("checkPasswordEmpty runs");
    if (this.myPassword) {
        // enable the button
    }
}
like image 549
Hongbo Miao Avatar asked Feb 20 '16 22:02

Hongbo Miao


People also ask

How do I disable the input button is empty?

Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.

How do I disable the button if the input box is empty and enable when field is filled in angular?

The main thing you need is a template variable, in my case it is #register="ngForm" , and you will use it for validating the form at the submit button, by setting its value to disabled attribute like [disabled]="!


1 Answers

In this case, I would leverage form validators. I would add the "required" validation on your input and use the global state of your form to disable / enable your button.

With the template-driven approach, there is no code to add in your component, only stuff in its template...

Here is sample below:

<form #formCtrl="ngForm">
  <input ngControl="passwordCtrl" required>
  <button [disabled]="!formCtrl.form.valid">Some button</button>
</form>
like image 127
Thierry Templier Avatar answered Sep 19 '22 18:09

Thierry Templier