我在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"
部分似乎起作用,但是我无法使用true
将其值设置为(click)="btn + i.id=true"
。如何连接btn
和i.id
并将其值设置为true?
感谢您的帮助!
答案 0 :(得分:2)
开头的代码(可能有错误):
在.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>
答案 1 :(得分:0)
分析以下代码
<div class="card" *ngFor="let i of items">
<button type="button" [disabled]="item.clicked" (click)="item.clicked=true">TEST</button>
<div>
这就是应在Angular中实现的方式。
如果您想知道在组件中单击了哪个按钮。然后添加“被点击” 属性在 items 数组中,然后在组件中使用它。