Sandra Willford
Sandra Willford

Reputation: 3789

ng if/else in a loop with multiple conditions

I am trying to sort out how to accomplish this. I have a button group that gets generated in an ngFor loop:

<div class="btn-group float-right">
    <button *ngFor="let frequency of mapping?.frequency_mapping" [ngClass]="[profile?.frequency_name == frequency.label ? 'btn-success' : 'btn-outline-secondary']" type="button" value="{{ frequency.pk}}" class="btn">{{ frequency.label }}</button>
</div>

and where i add the text for the button, I would like to insert a class based on the value of this button's frequency.label

so something like this:

if frequency.label = condition A then class = classA
else if frequency.label = condition B then class = classB
else if frequency.label = condition C then class = classB

what would the best way to accomplish this?

basically i need the end result to be something like

<button><i class="fa fa-classA"></i>{{ frequency.label }}</button>
<button><i class="fa fa-classB"></i>{{ frequency.label }}</button>
<button><i class="fa fa-classC"></i>{{ frequency.label }}</button>

Upvotes: 0

Views: 402

Answers (1)

Hugo Noro
Hugo Noro

Reputation: 3243

I believe you’re just using the wrong format on ngClass. Get rid of the [ ] brackets.

Have a look here

The case scenario you’re looking for is the 4th example on the “How to Use” section. You need it to evaluate an expression.

By using the brackets ngClass will be expecting an array of static strings for the styles, it will not evaluate the expression.

Upvotes: 1

Related Questions