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>
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
I would recommend the following.
<button [disabled]="isInvalid()">Submit</button>
Yes you can
<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
(click)="toggle(!isOn)">
Click me!
</div>
https://angular.io/docs/ts/latest/api/common/NgClass-directive.html
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
Using ngClass
to disabled the button for invalid form is not good practice in Angular2 when its providing inbuilt features to enable and disable the button if form is valid and invalid respectively without doing any extra efforts/logic.
[disabled]
will do all thing like if form is valid then it will be enabled and if form is invalid then it will be disabled automatically.
See Example:
<form (ngSubmit)="f.form.valid" #f="ngForm" novalidate>
<input type="text" placeholder="Name" [(ngModel)]="txtName" name="txtname" #textname="ngModel" required>
<input type="button" class="mdl-button" [disabled]="!f.form.valid" (click)="onSave()" name="">
May be below code can help:
<button [attr.disabled]="!isValid ? true : null">Submit</button>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With