typescript ngIf 设置颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38873480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:44:22  来源:igfitidea点击:

ngIf to set a color?

angulartypescript

提问by Eduard Arevshatyan

i have this json:

我有这个json:

[{
    "nodename": "Main application Server",
    "enabled": true
},
 {
    "nodename": "Main Server",
    "enabled": false
}]

and i show this data in my template with ngFor:

我用 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-primaryin 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?

现在,我会在我panel-primary的模板上设置不同的颜色:如果"enabled": true,则设置为绿色,如果"enabled": false,则设置为红色。这怎么办?与ngIf=...?或者是其他东西?

回答by Thierry Templier

You could leverage the ngStyle directive:

您可以利用 ngStyle 指令:

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

or ngClass:

或 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 }
    `
  ]
})

回答by tymeJV

You'd create a CSS class - and toggle the class via ngClass

您将创建一个 CSS 类 - 并通过切换类 ngClass

<div class="panel panel-primary" ng-class="{'green-class': list.enabled, 'red-class' : !list.enabled }">