Eduard Arevshatyan Eduard Arevshatyan - 3 months ago 11
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>
</div>
</div>
</div>
<div>


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

Answer

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:

@Component({
  (...)
  styles: [
    `
      .greenClass { background-color: green }
      .redClass { background-color: red }
    `
  ]
})
Comments