Search code examples
javascriptangularbindingngforng-class

ngClass used with ngFor in Angular to toggle icons


I have this piece of code from component.html

<div *ngFor="let passenger of passengers; let i=index">
  {{ passengers[i].child ? 'Child' : "" }}
  Name: {{ passengers[i].name }}
  Seat: {{ seats[i]}}
  Extra luggage: {{ passengers[i].luggage ? 'Yes' : 'No' }}
</div>

Instead of having Yes or No for the luggage part, which is depending on the user choice, I would like to show icon (suitcase if luggage = true, and strikethrough icon if luggage = false)

I was thinking about doing this with ngClass but I'm not sure how to properly do it due to the fact that those divs are iterated via ngFor and their number depends on user's choice as well.

<div [ngClass]="['greenIcon', 'redIcon']">Luggage</div>

Thanks in advance!


Solution

  • It depends on what icon method/library you're using but

    You should be able to use [ngClass] and simplify it to this:

    <div *ngFor="let passenger of passengers; let i = index">
        {{ passenger.child ? 'Child' : "" }}
        Name: {{ passenger.name }}
        Seat: {{ seats[i]}}
        Extra luggage: 
        <div [ngClass]="{'greenIcon': passenger.luggage, 'redIcon': !passenger.luggage}">
            {{ passenger.luggage ? 'Yes' : 'No' }}
        </div>
    </div>
    

    [ngClass] can be used as a dictionary with the classes being the keys and a boolean for the value to determine if it should be applied. NgClass

    [ngClass]="{ 'class-name': true }"