Angular2 disable button

前端 未结 10 1758
萌比男神i
萌比男神i 2020-12-02 10:03

I know that in angular2 I can disable a button with the [disable] attribute, for example:

相关标签:
10条回答
  • 2020-12-02 10:43

    If you have a form then the following is also possible:

    <form #f="ngForm">
        <input name="myfield" type="text" minlenght="3" required ngModel>
        <button type="submit" [disabled]="!f.valid">Submit</button>
    </form>
    

    Demo here: http://plnkr.co/edit/Xm2dCwqB9p6WygrquUGh?p=preview&open=app%2Fapp.component.ts

    0 讨论(0)
  • 2020-12-02 10:47

    May be below code can help:

    <button [attr.disabled]="!isValid ? true : null">Submit</button>
    
    0 讨论(0)
  • 2020-12-02 10:49

    I think this is the easiest way

    <!-- Submit Button-->
    <button 
      mat-raised-button       
      color="primary"
      [disabled]="!f.valid"
    >
      Submit
    </button>
    
    0 讨论(0)
  • 2020-12-02 10:50

    I tried using disabled along with click event. Below is the snippet , the accepted answer also worked perfectly fine , I am adding this answer to give an example how it can be used with disabled and click properties.

    <button (click)="!planNextDisabled && planNext()" [disabled]="planNextDisabled"></button>
    
    0 讨论(0)
  • 2020-12-02 10:52

    I would recommend the following.

    <button [disabled]="isInvalid()">Submit</button>
    
    0 讨论(0)
  • 2020-12-02 10:55

    Update

    I'm wondering. Why don't you want to use the [disabled] attribute binding provided by Angular 2? It's the correct way to dealt with this situation. I propose you move your isValid check via component method.

    <button [disabled]="! isValid" (click)="onConfirm()">Confirm</button>
    

    The Problem with what you tried explained below

    Basically you could use ngClass here. But adding class wouldn't restrict event from firing. For firing up event on valid input, you should change click event code to below. So that onConfirm will get fired only when field is valid.

    <button [ngClass]="{disabled : !isValid}" (click)="isValid && onConfirm()">Confirm</button>
    

    Demo Here

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