Search code examples
angularbuttonngfordisable

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. 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!


Solution

  • 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>