简体   繁体   English

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

[英]Angular4: Disable button in ngFor after click

I have a <button> in a ngFor loop and I want it to be disabled after the user clicks on the button. 我在ngFor循环中有一个<button> ,我希望在用户单击按钮后将其禁用。 There is a button for each element of the loop so I have to differentiate them using a different boolean value for each of them. 循环的每个元素都有一个按钮,因此我必须为每个元素使用不同的布尔值来区分它们。

Here is a code snippet from the html: 这是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" part seems to work, but i cant set the value of it to true using (click)="btn + i.id=true" . [disabled]="'btn' + i.id"部分似乎正常工作,但是我无法使用(click)="btn + i.id=true"将其值设置为true How can I concatenate the btn and i.id and set the value of it to true? 如何连接btni.id并将其值设置为true?

Any help is appreciated! 任何帮助表示赞赏!

Code from head (can have bugs): 从头开始的代码(可能有错误):

In your .ts component use array: 在您的.ts组件中,使用数组:

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

In your template: 在您的模板中:

<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 works on Angular 5/6, for lower version use let j=index index as jindex as j适用于Angular 5/6,对于较低版本,请使用let j=index

Alternative solution 替代解决方案

Add to items field disabled and use that field directly: 禁用添加到项目字段,并直接使用该字段:

<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. 这就是应该在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. 然后在items数组中添加“ clicked”属性,然后在组件中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM