67

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">

3 Answers 3

155
[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

Sign up to request clarification or add additional context in comments.

4 Comments

There are different ways and the alternatives might be more convenient in other situations.
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.
"new question" - I guess this would be a good idea. I guess it needs more details (code) to diagnose.
what is the best way to do this programmatically, from .ts class?
4

Try this one:

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

Comments

1

bind- prefix alternative can be used also as below

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

1 Comment

What is the advantage of this over simply [style.background-color]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.