Angular2 disable button

Nir Schwartz picture Nir Schwartz · Feb 21, 2016 · Viewed 210.8k times · Source

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

Pankaj Parkar picture Pankaj Parkar · Feb 21, 2016

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