Angular4: Disable button in ngFor after click
Asked Answered
N

2

5

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!

Niple answered 13/11, 2018 at 8:40 Comment(0)
R
7

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>
Ropable answered 13/11, 2018 at 8:46 Comment(1)
Τhanks! Works just like I wanted it to.Niple
S
1

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.

Shanty answered 13/11, 2018 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.