【发布时间】:2019-03-01 15:57:30
【问题描述】:
我是 Angular 的新手,我想知道在单击同一个按钮并执行相应操作后如何禁用该按钮
这是我的按钮 html 代码
<button type="button" class="btn btn-primary" (click)="actionMethod()">Give Kitchen access</button> <br> <br>
【问题讨论】:
标签: javascript html angular
我是 Angular 的新手,我想知道在单击同一个按钮并执行相应操作后如何禁用该按钮
这是我的按钮 html 代码
<button type="button" class="btn btn-primary" (click)="actionMethod()">Give Kitchen access</button> <br> <br>
【问题讨论】:
标签: javascript html angular
您可以将disabled 属性绑定到一个标志(例如clicked),并在click 事件处理程序中设置该标志:
<button type="button" [disabled]="clicked" (click)="actionMethod(); clicked = true;" class="btn btn-primary">Give Kitchen access</button>
标志应该在组件类中声明:
clicked = false;
请参阅this stackblitz 以获取演示。
【讨论】:
<button type="button" class="btn btn-primary" (click)="actionMethod($event)">Give Kitchen access</button>
actionMethod(event: any) {
event.target.disabled = true;
}
【讨论】:
<button (click)="actionMethod($event)"><span>Click here</span></button> 的东西,target 元素可能指的是跨度,而不是按钮。因此,当在按钮中使用子元素时,event.currentTarget.disabled = true 会很有帮助。
TypeScript 实现
如果您使用的是 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,这是最好的解决方案,因为您不必在 Component ts 文件中保留布尔值,并且可以获得 TypeScript 的类型。
【讨论】:
<button (click)="submit();submitButton.disabled = true" #submitButton>submit</button>
【讨论】:
例如,如果您有由 *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)
}
【讨论】: