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

Angular4: Disable button in ngFor after click

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

这是来自 html 的代码片段:

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

[disabled]="'btn' + i.id" 部分似乎有效,但我无法使用 (click)="btn + i.id=true" 将它的值设置为 true。如何连接 btni.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>

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

备选方案

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

<button type="button" [disabled]="item.disabled" (click)="item.disabled=true">TEST</button>

Analyze below code

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

This is how it should be implemented in Angular.

If you want to know which button gets clicked in your component. Then add 'clicked' property in items array and then use it in the component.