Eduard Arevshatyan Eduard Arevshatyan - 1 year ago 135
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?

Answer Source

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 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download