[英]How to disable button after (click) in Angular
我是 Angular 的新人,我想知道如何在单击同一个按钮并执行对应的操作后禁用该按钮
这是我的按钮 html 代码
<button type="button" class="btn btn-primary" (click)="actionMethod()">Give Kitchen access</button> <br> <br>
您可以将disabled
属性绑定到一个标志(例如clicked
),并在click
事件处理程序中设置该标志:
<button type="button" [disabled]="clicked" (click)="actionMethod(); clicked = true;" class="btn btn-primary">Give Kitchen access</button>
该标志应在组件类中声明:
clicked = false;
有关演示,请参阅 此 stackblitz 。
<button type="button" class="btn btn-primary" (click)="actionMethod($event)">Give Kitchen access</button>
actionMethod(event: any) {
event.target.disabled = true;
}
允许厨房访问
actionMethod(){
打字稿实现
如果您使用的是 Angular,那么您可能正在使用 TypeScript。 这是 TypeScript 实现(受 @DanielWilliams 的 js 实现启发):
组件html
<button type="button" class="btn btn-primary" (click)="actionMethod($event)">Give Kitchen access</button>
组件 ts
actionMethod($event: MouseEvent) {
($event.target as HTMLButtonElement).disabled = true;
// Do actions.
}
这,IMO,是卓越的解决方案,因为您不必在组件 ts 文件中保留布尔值,并且您可以获得 TypeScript 的类型。
例如,如果您有通过 *ngFor 循环在模板中生成的按钮,您可能只想禁用一个被单击的按钮。 为此,您必须确定点击了哪个。 您可以将单击的按钮存储在数组中。 如果单击按钮,它会被推送到数组,以禁用它。 在指定的时间后,您可以从数组中删除按钮,以启用它。
在 html 模板中:
<ng-container *ngFor="let button of buttons">
<button mat-stroked-button
#button
(click)="disableButton(button)"
[disabled]="disabledButtons.includes(button)">
</button>
</ng-container>
在 component.ts 添加:
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)
}
您还可以使用 css 来禁用事件。
[ngStyle]="{'pointer-events': (condition)? 'none': 'all'}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.