'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" class="btn btn-primary" (click)="actionMethod()">Give Kitchen access</button> <br> <br>
Solution 1:[1]
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;" class="btn btn-primary">Give Kitchen access</button>
The flag should be declared in the component class:
clicked = false;
See this stackblitz for a demo.
Solution 2:[2]
<button type="button" class="btn btn-primary" (click)="actionMethod($event)">Give Kitchen access</button>
actionMethod(event: any) {
event.target.disabled = true;
}
Solution 3:[3]
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" class="btn btn-primary" (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.
Solution 4:[4]
A template reference approach:
<button (click)="submit();submitButton.disabled = true" #submitButton>submit</button>
Solution 5:[5]
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)
}
Solution 6:[6]
You can also use css to disable events.
[ngStyle]="{'pointer-events': (condition) ? 'none' : 'all'}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ConnorsFan |
| Solution 2 | Daniel Williams |
| Solution 3 | Patrick |
| Solution 4 | JayChase |
| Solution 5 | |
| Solution 6 | Andrés Miranda |
