本文介绍了Angular2-根据值为元素设置不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Angular2
的新手,想知道如何根据值将字体颜色设置为元素.
I am new to Angular2
and was wondering how I go about setting a font color to an element depending on the value.
我的情况是:如果输入字段的值不是100,那么我希望它是红色,但是如果它是100,那么我希望它是绿色.
My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.
我有以下代码,但是无法正常工作.
I have the following code in place but cant get it working.
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>
推荐答案
有两种解决方案来更改字体颜色,但要取决于您的要求
There are two solutions to change font color but depends on you requirement
- 如果您需要更改嵌入式样式,则可以使用有角的
NgStyle
指令,该指令为您更新HTML元素样式.
- If you requirement is change inline style then you can use angular
NgStyle
Directive which Update an HTML element styles for you..
NgStyle directive Ex:
<span [ngStyle]="{'color': proportion === '100' ? 'green' : 'red'}"></span>
---------------------- OR -----------------------------------
<span [style.color]="proportion === '100' ? 'green' : 'red'"></span>
- 如果您需要更改类,则可以使用angular
NgClass
指令,该指令在HTML元素上添加和删除CSS类...
- If you requirement is change class then you can use angular
NgClass
Directive which Adds and removes CSS classes on an HTML element...
NgClass directive Ex:
<span [ngClass]="{proportion === '100' ? 'green': 'red'}"></span>
这篇关于Angular2-根据值为元素设置不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!