Angular4: Disable button in ngFor after click

空扰寡人 提交于 2019-12-10 23:54:42

问题


I have a <button> in a ngFor loop and I want it to be disabled after the user clicks on the 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:

<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". How can I concatenate the btn and i.id and set the value of it to true?

Any help is appreciated!


回答1:


Code from head (can have bugs):

In your .ts component use array:

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

Alternative solution

Add to items field disabled and use that field directly:

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



回答2:


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.



来源:https://stackoverflow.com/questions/53276941/angular4-disable-button-in-ngfor-after-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!