根据值更改图标颜色

时间:2017-02-02 07:11:33

标签: html css angular typescript ng-class

我是Angular2的新手,我想知道如何根据值有条件地更改图标的CSS。

在HTML中:

<li><i class="fa fa-check" [style.color]="'switch(types)'"></i>{{ types }}</li>

类型包含很多1-3的整数范围。

在ts:

switch(p) {
    if(p==0) {...} //return color red
    if(p==1) {...} //return color blue
    if(p==2) {...} //return color green
}

这对我来说似乎不起作用。

4 个答案:

答案 0 :(得分:1)

切换在其缺失的正文中使用大小写。其他方式是使用函数绑定(这不是首选)但找不到任何其他解决方案。

[style.color]="color(types)"


color(p) {
    if(p==0) {return 'green'} 
    if(p==1) {return 'red'} 
    if(p==2) {return 'blue'} 
}

DEMO https://plnkr.co/edit/zQ79mbS2U3X1s9ktnTIR?p=preview

答案 1 :(得分:1)

   <li>
        <i class="fa fa-check" [ngStyle]="{'color': switch(types)}"> 
            {{types}}
        </i>   
   </li>


switch(p) {
    if(p==0) {return 'red'} 
    if(p==1) {return 'blue'} 
    if(p==2) {return 'green'} 
}

答案 2 :(得分:0)

已经回答,但另一种可能的方法。

对于一组有限的值,您也可以在[ngClass]内部执行此操作。看起来像

gateway()

这是有效的,因为值是独立的。您还必须在css文件中声明新类。

[ngClass]="{'red':types === 0,
  'blue':types === 1,
  'green':types === 2}"

这应减少每次运行时重新计算布局时必须调用方法的开销。这种方法可能就是我用于您的示例的方法。对于更复杂的条件或更大的值集,我可能会使用函数调用方法。

答案 3 :(得分:-1)

你可以这样做:

<li><i class="fa fa-check" [ngStyle]="changeCSS(types)"></i>{{ types }}</li>


      changeCSS(types:any){
    let style:any;
      if(types == 0){
        style={
          'background':'..',
          'border-color':'....',
          'border-bottom': '...',

        }
    }
return style;
}

希望这有帮助

EDIt:已根据建议删除了''

相关问题