【问题标题】:How to use ngClass with conditional statements如何在条件语句中使用 ngClass
【发布时间】:2019-04-17 14:09:36
【问题描述】:

我的垫子图标元素的颜色应该是动态变化的。

<mat-icon class="temperature icon" svgIcon="thermometer-alert" matTooltip = {{temp_tooltip}}
          aria-label="Icon that displays a tooltip when focused or hovered over"
          [ngClass]= "{
            'safe' : 23 <= temp_tooltip <= 24.5,
            'alarm_lowside' : 21 <= temp_tooltip < 23,
            'alarm_highside' : 24.5 < temp_tooltip <= 26, 
            'critical_lowside' : temp_tooltip < 21,
            'critical_highside' : temp_tooltip > 26
           }" >
        </mat-icon>

temp_tooltip 值绑定在 component.ts 中

css 有颜色样式

.safe {
 color: green
}

.alarm_lowside {
    color: yellow
}

.alarm_highside {
    color: yellow
}

.critical_lowside {
    color: red
}

.critical_highside{
    color: red
}

它适用于critical_lowside 和critical_highside 类,但不适用于其他类。如何纠正。 ngClass的定义方式是否正确?

【问题讨论】:

  • 将您的条件更改为:temp_tooltip &gt;= 23 &amp;&amp; temp_tooltip &lt;= 24.5, ... 对所有人都这样做。

标签: html angular typescript ng-class angular-ng-if


【解决方案1】:

23 &lt;= temp_tooltip &lt;= 24.5 不是 javascript/typescript 中的正确表达式。

您应该找到另一种表达这种情况的方式,例如 23 &lt;= temp_tooltip &amp;&amp; temp_tooltip &lt;= 24.5

【讨论】:

    【解决方案2】:

    正确的语法是这样的:

     [ngClass]= "{
            'safe' : temp_tooltip >= 23 && temp_tooltip <= 24.5,
            'alarm_lowside' : temp_tooltip >= 21 && temp_tooltip < 23,
            'alarm_highside' : temp_tooltip > 24.5 && temp_tooltip <= 26, 
            'critical_lowside' : temp_tooltip < 21,
            'critical_highside' : temp_tooltip > 26
       }"
    

    【讨论】:

      猜你喜欢
      • 2015-01-10
      • 2011-06-21
      • 2021-02-22
      • 2018-04-04
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多