Reputation: 5077
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>
Upvotes: 30
Views: 93437
Reputation: 1
You can also use css to disable events.
[ngStyle]="{'pointer-events': (condition) ? 'none' : 'all'}"
Upvotes: -2
Reputation: 6255
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)
}
Upvotes: 0
Reputation: 11535
A template reference approach:
<button (click)="submit();submitButton.disabled = true" #submitButton>submit</button>
Upvotes: 5
Reputation: 14378
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.
Upvotes: 9
Reputation: 692
<button type="button" class="btn btn-primary" (click)="actionMethod($event)">Give Kitchen access</button>
actionMethod(event: any) {
event.target.disabled = true;
}
Upvotes: 28
Reputation: 73791
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.
Upvotes: 55