本文介绍了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

  1. 如果您需要更改内联样式,那么您可以使用 angular NgStyle 指令,它为您更新 HTML 元素样式..
  1. If you requirement is change inline style then you can use angular NgStyle Directive which Update an HTML element styles for you..

NgStyle 指令示例:

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

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

<span [style.color]="proportion === '100' ? 'green' : 'red'"></span>
  1. 如果您的要求是更改类,那么您可以使用 angular NgClass 指令,该指令在 HTML 元素上添加和删除 CSS 类...
  1. If you requirement is change class then you can use angular NgClass Directive which Adds and removes CSS classes on an HTML element...

NgClass 指令示例:

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

这篇关于Angular2 - 根据值为元素设置不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 19:46