56

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
  • 6,736
  • 10
  • 49
  • 101

3 Answers3

132
[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
  • 558,509
  • 191
  • 1,911
  • 1,506
  • 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
2

Try this one:

[ngStyle]="{'border': user?.keyResults.percentage > 50 ? '3px solid green' : '3px solid red' }"
Tomislav Stankovic
  • 3,090
  • 16
  • 33
  • 41
1

bind- prefix alternative can be used also as below

bind-style.background-color="activity.status == 'Pending' ? 'red' : 'green'"
ElasticCode
  • 6,525
  • 2
  • 27
  • 41