Set style dynamically in Angular

Angular

Angular Problem Overview


I have following markup

<tr *ngFor='let activity of pagedWorkflowActivities' style="background-color:{{activity.status == 'Pending' ? 'red' : 'green'}}">
.
.
.
.
</tr>

As it says, if activity.status field is pending then make background color red otherwise green. But it doesn't work. After inspecting I found it renders it like

<tr ng-reflect-style="unsafe">

Angular Solutions


Solution 1 - Angular

[style.background-color]="activity.status == 'Pending' ? 'red' : 'green'"

or

[ngStyle]="{'backgroundColor': activity.status == 'Pending' ? 'red' : 'green' }"

For your rendering result see also https://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax/37076868#37076868

Solution 2 - Angular

Try this one:

[ngStyle]="{'border': user?.keyResults.percentage > 50 ? '3px solid green' : '3px solid red' }"

Solution 3 - Angular

bind- prefix alternative can be used also as below

bind-style.background-color="activity.status == 'Pending' ? 'red' : 'green'"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionImadView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularNishat Tasnim MithilaView Answer on Stackoverflow
Solution 3 - AngularElasticCodeView Answer on Stackoverflow