javascript 如何在 Angular 中(单击)后禁用按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52508126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:57:33  来源:igfitidea点击:

How to disable button after (click) in Angular

javascripthtmlangular

提问by José Nobre

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

我是 Angular 的新手,我想知道如何在单击同一按钮并执行相应操作后禁用该按钮

This is my button html code

这是我的按钮 html 代码

<button type="button" class="btn btn-primary" (click)="actionMethod()">Give Kitchen access</button> <br> <br>

回答by ConnorsFan

You can bind the disabledproperty to a flag (e.g. clicked), and set the flag in the clickevent handler:

您可以将该disabled属性绑定到一个标志(例如clicked),并在click事件处理程序中设置该标志:

<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 stackblitzfor a demo.

有关演示,请参阅此 stackblitz

回答by Daniel Williams

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

回答by Patrick

TypeScript implementation

打字稿实现

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

如果您使用的是 Angular,那么您可能正在使用 TypeScript。这是 TypeScript 实现(受@DanielWilliams 的 js 实现启发):

Component html

组件html

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

Component ts

组件 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.

这,IMO,是卓越的解决方案,因为您不必在组件 ts 文件中保留布尔值,并且您可以获得 TypeScript 的类型。

回答by JayChase

A template referenceapproach:

一个模板参考方法:

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

StackBlitz

闪电战