Disable button when input is empty in Angular 2

后端 未结 3 1263
谎友^
谎友^ 2021-01-04 02:37

I want to check whether the input is empty.

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

I tried

相关标签:
3条回答
  • 2021-01-04 03:10

    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>
    
    0 讨论(0)
  • 2021-01-04 03:13

    To bind functions to events, you don't have to prefix them with on. Just place the event.

    For example, if you want to handle the keydown (plunker demo):

    <input type="password" [(ngModel)]="myPassword" (keydown)="checkPasswordEmpty($event)"/>
    

    But in your specific case, since you already are using ngModel you are better off using (ngModelChange):

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

    Because it will pick up the changes when the user pastes (via CTRL+V ormouse right click menu -> Paste) the password instead of typing it.

    See plunker demo for using (ngModelChange) here.

    0 讨论(0)
  • 2021-01-04 03:17

    When using the template-driven approach suggested by @Thierry Templier, the form object also has an invalid property.

    So instead of:

    <button [disabled]="!formCtrl.form.valid">Some button</button>
    

    You can also use:

    <button [disabled]="formCtrl.form.invalid">Some button</button>
    

    It's a small difference, but overall cleaner syntax in my opinion.

    0 讨论(0)
提交回复
热议问题