How to disable button after (click) in Angular

I am new at Angular, and I would like to know how to disable a button after I click that same button and performed the action correspondent

This is my button html code

<button type="button" (click)="actionMethod()">Give Kitchen access</button> <br> <br> 

6 Answers

You can bind the disabled property to a flag (e.g. clicked), and set the flag in the click event handler:

<button type="button" [disabled]="clicked" (click)="actionMethod(); clicked = true;">Give Kitchen access</button> 

The flag should be declared in the component class:

clicked = false; 

See this stackblitz for a demo.

3
<button type="button" (click)="actionMethod($event)">Give Kitchen access</button> 
actionMethod(event: any) { event.target.disabled = true; } 
1

TypeScript implementation

If you're using Angular, you're probably using TypeScript. Here's the TypeScript implementation (inspired by @DanielWilliams' js implementation):

Component html

<button type="button" (click)="actionMethod($event)">Give Kitchen access</button> 

Component ts

actionMethod($event: MouseEvent) { ($event.target as HTMLButtonElement).disabled = true; // Do actions. } 

This, IMO, is the superior solution because you don't have to keep booleans around in your Component ts files and you get TypeScript's types.

1

A template reference approach:

 <button (click)="submit();submitButton.disabled = true" #submitButton>submit</button> 

StackBlitz

If you have buttons generated in template by a *ngFor loop, for example, you may want to disable only one button that was clicked on. For that you have to idendify which one was clicked on. You could store clicked buttons in array. If button is clicked on, it's pushed to array, to disable it. After specified time you can remove the button from array, to enable it.

In html template:

 <ng-container *ngFor="let button of buttons"> <button mat-stroked-button #button (click)="disableButton(button)" [disabled]="disabledButtons.includes(button)"> </button> </ng-container> 

In component.ts add:

 buttons = [1,2,3] disabledButtons = []; // Disables click button for period of 2 seconds disableButton(button: any) { this.disabledButtons.push(button); setTimeout(() => { this.disabledButtons.splice(this.disabledButtons.indexOf(button), 1); },2000) } 

See stackblitz

You can also use css to disable events.

[ngStyle]="{'pointer-events': (condition) ? 'none' : 'all'}"

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like