Nir Schwartz Nir Schwartz - 6 months ago 454
HTML Question

Angular2 disable button

I know that in angular2 I can disable a button with the

[disable]
attribute, for example:

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


but can I do it using
[ngClass]
or
[ngStyle]
? Like so:

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


Thanks.

Answer

Basically you could use ngClass here. But adding class wouldn't restrict event to fire. 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

But still I'm in big question, why you don't wanted to use [disabled] attribute binding provided by angular2? Its more preferred solution to with it.

Comments