'Changing background color using ngClass and boolean is not working correctly?

I am trying to check an object coming in a back-end response to see if error.isCritical is true or false and setting the ngClass accordingly, i've tried many different approaches, but this is the one i am using right now:

Angular/HTML:

<p-table>
    <ng-template pTemplate="header">
        <tr *ngFor="let error of errors" 
            [ngClass]="{critical: error.isCritical, notCritical: 
            !error.isCritical}">
             <td width="25%">
                {{ error.dateRange['start'] }} to
                {{ error.dateRange['end'] }}
             </td>
             <td width="25%">{{ error.processId }}</td>
             <td width="50%">{{ error.message }}</td>
        </tr>
     </ng-template>
</p-table>

CSS:

.critical{
  background-color: red;
}
.notCritical{
  overflow: hidden;
  background-color: white;
  padding: 5px;
  color: black;
}

It seems to either make them all red background, or all white background no matter what i try, and i have checked the backend call and the isCritical flag is false for some and true for others, so i can't figure out why they are all red when they are red?

Any Help would be greatly appreciated.



Solution 1:[1]

You can dynamically add classes using the code below:

[ngClass]="{'critical': error.isCritical, 'notCritical' : !error.isCritical }"

Solution 2:[2]

you can try different syntax (Angular 2+)

type one

[class.my_class] = "step === 'step1'"

type two

[ngClass]="{'my_class': step === 'step1'}"

and multiple option:

[ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"

type three

[ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"

type four

[ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"

Solution 3:[3]

Replace your code with below code:

<p-table>
    <ng-template pTemplate="header">
        <tr *ngFor="let error of errors" 
   [ngClass]="[error.isCritical ? 'critical' : 'notCritical']">
             <td width="25%">
                {{ error.dateRange['start'] }} to
                {{ error.dateRange['end'] }}
             </td>
             <td width="25%">{{ error.processId }}</td>
             <td width="50%">{{ error.message }}</td>
        </tr>
     </ng-template>
</p-table>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leon Matota
Solution 2 Abhishek Upadhyay
Solution 3 Nensi Gondaliya