Home > Net >  Changing background color using ngClass and boolean is not working correctly?
Changing background color using ngClass and boolean is not working correctly?

Time:04-29

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.

CodePudding user response:

You can dynamically add classes using the code below:

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

CodePudding user response:

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'"
  • Related