Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Conditionally change background color of element

I have recently made a new project in Angular 6, and all my previous experience is in Angular 1.5.

I would like to control the background color of an item in my HTML page, based on its text value.

  • VALID: Green
  • PAUSED: Orange
  • INVALID: Red

Is there a way to do this specifically with Angular methods like ngStyle or something, rather than just writing a jQuery function in the component to change the CSS class based on the value?

<span class="producerState">{{prod.producerState}}</span>

Change background of .producerState span based on the textual value.

like image 675
Cody Pritchard Avatar asked Oct 18 '18 22:10

Cody Pritchard


1 Answers

First of all you should never use JQuery and Angular together.

and you can use ngStyle

[ngStyle]="yourText=='INVALID'?{'background-color':'red'} : {'background-color': 'white'}"

or ngClass

[ngClass]="{'invalidClass': yourText=='INVALID'}">
like image 96
Or Yaacov Avatar answered Nov 02 '22 00:11

Or Yaacov