Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set style dynamically in Angular

Tags:

angular

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"> 
like image 409
Imad Avatar asked Nov 18 '16 11:11

Imad


People also ask

How to set CSS dynamically in Angular?

The NgClass Directive in AngularThe NgClass directive allows you to set the CSS class dynamically for a DOM element. When using an object literal, the keys are the classes which are added to the element if the value of the key evaluates to true.

What is dynamic in angular?

Dynamic means, that the components location in the application is not defined at buildtime. That means, that it is not used in any angular template. Instead, the component is instantiated and placed in the application at runtime.

What is the difference between style and ngStyle?

ngStyle is an Angular directive that gives you the flexibility to do this, where as style is a regular HTML property to which you can only bind values one by one. That's the difference between the two of them.


1 Answers

[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

like image 174
Günter Zöchbauer Avatar answered Sep 16 '22 21:09

Günter Zöchbauer