Angular2 - 根据值为元素设置不同的颜色

Angular2 - Set A Different Color to an element Depending On Value

我是 Angular2 的新手,想知道如何根据值为元素设置字体颜色。

我的场景是:如果输入字段的值不是 100,那么我希望它是红色的,但是如果它是 100,那么我希望它是绿色的。

我有以下代码,但无法正常工作。

XXX.component.css

.red {
    color: red; 
}

.green {
    color: green;
}

XXX.component.css

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">
<p>hello <span ng-class='{red : proportion!= '100', green: proportion === '100'}'>{{proportion}}</span></p>

你可以这样使用它:

 <div class="card template-card" [ngClass]="{'z-depth-3': template == selectedTemplate, 'not-selected': !(template == selectedTemplate) && selectedTemplate != null}">

您需要修改您的逻辑以使用双引号和 ngModel 比例

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion">
<p>hello <span [ngClass]="{red : proportion != '100', green: proportion === '100'}">{{username}}</span></p>

希望对您有所帮助!!

因为你用了Angular2,所以你需要用[ngClass],而你的输入模型绑定到proportion,所以用它来比较,

这样做:

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion">
<p>hello <span [ngClass]="{'red': proportion !== '100', 'green': proportion === '100'}">{{username}}</span></p>

有两种更改字体颜色的解决方案,但取决于您的要求

  1. 如果您的要求是更改内联样式,那么您可以使用 angular NgStyle 指令为您更新 HTML 元素样式..

NgStyle directive Ex:

<span [ngStyle]="{'color': proportion === '100' ? 'green' : 'red'}"></span>

        ---------------------- OR -----------------------------------

<span [style.color]="proportion === '100' ? 'green' : 'red'"></span>
  1. 如果您的要求是更改 class 那么您可以使用 angular NgClass 指令在 [=31] 上添加和删除 CSS classes =] 元素...

NgClass directive Ex:

<span [ngClass]="{proportion === '100' ? 'green': 'red'}"></span>

也可以绑定样式属性。

<span [style.color]="proportion === '100' ? 'green' : 'red'"></span>