Eduard Arevshatyan Eduard Arevshatyan - 5 months ago 15
TypeScript Question

ngIf to set a color?

i have this json:

"nodename": "Main application Server",
"enabled": true
"nodename": "Main Server",
"enabled": false

and i show this data in my template with ngFor:

<div class="row" *ngFor="let list of lists">
<div class="col-md-12 col-xs-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h2 class="panel-title text-center">Server: {{ list.nodename }}, {{ list.enabled }}</h2>

And now, i would set to different color on my
in template: if
"enabled": true
, than set a green color, and if
"enabled": false
, set a red color. How do this? with
? Or something else?


You could leverage the ngStyle directive:

<div class="panel panel-primary"
    [ngStyle]="{'background-color': list.enabled? 'green' : 'red'}">

or ngClass:

<div class="panel panel-primary"
    [ngClass]="{greenClass: list.enabled, redClass: !list.enabled}">

With the following styles in your component:

  styles: [
      .greenClass { background-color: green }
      .redClass { background-color: red }