63

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">
Imad
  • 7,126
  • 12
  • 55
  • 112

3 Answers3

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

or

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

For your rendering result see also In RC.1 some styles can't be added using binding syntax

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    There are different ways and the alternatives might be more convenient in other situations. – Günter Zöchbauer Nov 18 '16 at 11:45
  • I have seen this error message but I don't remember what caused it. A suggestion. Don't use method calls in view bindings (only event handlers) because this method will be called every time change detection runs. Also if the method returns a new object instance with every call like `return { a: b };`, you'll get an exception from Angulars change detection. Rather assign the result of the method call to a property and bind to that property, or if you still want to use a method, cache the result and return the cached instance in case the parameters haven't changed. – Günter Zöchbauer Nov 18 '16 at 11:55
  • 1
    "new question" - I guess this would be a good idea. I guess it needs more details (code) to diagnose. – Günter Zöchbauer Nov 18 '16 at 11:56
  • 1
    what is the best way to do this programmatically, from .ts class? – albanx Nov 11 '18 at 11:40
3

Try this one:

[ngStyle]="{'border': user?.keyResults.percentage > 50 ? '3px solid green' : '3px solid red' }"
Tomislav Stankovic
  • 3,080
  • 17
  • 35
  • 42
1

bind- prefix alternative can be used also as below

bind-style.background-color="activity.status == 'Pending' ? 'red' : 'green'"
ElasticCode
  • 7,311
  • 2
  • 34
  • 45