2
votes

I have an array with names and same array with statuses (true, false). I am iterating through all names and creating buttons, and I want the button class to be btn-success if status of that element is true, and btn-danger if it is false. How can I make it? I tried with [ngClass] but it does not work.

app.component.html:

<div
        *ngFor="let element of elements; let index = index"
        (click)="changeStatus(index)"
        [ngClass]="{'btn-success':statuses[index]===true}"
        [ngClass]="{'btn-danger':statuses[index]===false}">
        {{element}}
</div>

arrays in app.component.ts

  elements = ['Element 1', 'Element 2', 'Element 3', 'Element 4', 'Element 5'];
  statuses = [false, false, false, false, false];
2

2 Answers

3
votes
<button
        *ngFor="let element of elements; let index = index"
        [ngClass]="statuses[index]?'btn-success':'btn-danger'">
        {{element}}
</button>
2
votes

You can't use 2 of the ngClass directive.

The value that is passed to ngClass is just an object, so you need to comma separate the values within it, like so:

[ngClass]="{'btn-success':statuses[index]===true, 
            'btn-danger':statuses[index]===false}"

Here is a StackBlitz demonstration