Angular:单击后禁用 ngFor 中的按钮

2024-02-26

我有一个<button>在 ngFor 循环中,我希望在用户单击按钮后将其禁用。循环的每个元素都有一个按钮,因此我必须为每个元素使用不同的布尔值来区分它们。

这是 html 中的代码片段:

<div class="card" *ngFor="let i of items">
    <button type="button" [disabled]="'btn' + i.id" (click)="btn + i.id=true">TEST</button>
<div>

The [disabled]="'btn' + i.id"部分似乎有效,但我无法将其值设置为true using (click)="btn + i.id=true"。我怎样才能连接btn and i.id并将其值设置为true?

任何帮助表示赞赏!


头部代码(可能有错误):

在您的 .ts 组件中使用数组:

buttons = Array(10).fill(false); // e.g. 10 = size of items

在您的模板中:

<div class="card" *ngFor="let i of items; index as j">
    <button type="button" [disabled]="buttons[j]" (click)="buttons[j]=true">TEST</button>
<div>

The index as j适用于 Angular 5/6,适合较低版本使用let j=index

替代解决方案

添加到已禁用的项目字段并直接使用该字段:

<button type="button" [disabled]="item.disabled" (click)="item.disabled=true">TEST</button>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular:单击后禁用 ngFor 中的按钮 的相关文章

随机推荐