Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 723
Eduard Arevshatyan Avatar asked Aug 10 '16 12:08

Eduard Arevshatyan


1 Answers

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 }
    `
  ]
})
like image 64
Thierry Templier Avatar answered Oct 06 '22 00:10

Thierry Templier