5

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 Answers 2

5
<button
        *ngFor="let element of elements; let index = index"
        [ngClass]="statuses[index]?'btn-success':'btn-danger'">
        {{element}}
</button>
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.