Search code examples
angularngforng-class

Using ng-class within *ngFor to conditionally format table cell in Angular 11


I'm taking populating the contents of a table by using *ngFor to cycle through the contents of an array.

The table populates just fine, but I want to change the background of a cell based on the value it has been populated with (for example green if the value is "pass" and red if the value is "fail."

The approach I'm taking is to use ng-class to evaluate the content of the value of element of the array and using that to set the background - but it's not working.

Component HTML

<tr *ngFor="let e of list;">
        <td>{{ e.description}}</td>

        <td ng-class="{'Pass' : {{e.status}} =='Pass', 'Fail' : {{e.status}} =='Fail'}">{{ e.status }}
        </td></tr>

Component CSS

.Pass {
 
  background-color: green;
}

.Fail {
  background-color: red;
}

Solution

  • Solution:

    <tr *ngFor="let e of list;">
            <td>{{e.description}}</td>
            <td [ngClass]="{Pass: e.status === 'Pass', Fail: e.status === 'Fail'}">{{e.status}}
            </td>
            </tr>
    

    Or if the status can be either pass or fail - we can check the condition once with the ternary operator:

    [ngClass]="e.status=== 'Pass'? 'Pass' : 'Fail'"
    

    A few things:

    • CSS classes are usually not Capitalized.
    • You don't need to interpolate inside of ngClass.

      {'Pass' : {{e.status}} =='Pass', 'Fail' : {{e.status}} =='Fail'} <-- e.status not {{e.status}}

    • I would stick to the usual [ngClass] (there are other ways to apply a dynamic class in Angular, but this is the most used).