【问题标题】:Ng-Style Conditional Operators not working Angular 6Ng 风格的条件运算符不工作 Angular 6
【发布时间】:2019-08-24 13:38:47
【问题描述】:

更新

 <div style="margin-top: 10px; color: white; height: 50%; padding: 5%; font-size: 25px; font-weight: bold"
    [ngStyle]="{'background-color': global.timeSpent <= '10' ? 'LimeGreen' : ((global.timeSpent > '10' && global.timeSpent <= '20')  ? 'Gold' : 'Red' ) }">{{global.timeSpent}}</div>

二次接近

<div [ngStyle]="styleColor"> {{global.timeSpent}}</div>                   
styleColor(){
this.global.timeSpentToStoryPointVariance = this.global.timeSpentToStoryPointVariance.split('%')[0]

if(this.global.timeSpentToStoryPointVariance <= '10') {
return  '{ "background-color": "LimeGreen" }';
}
else if(this.global.timeSpentToStoryPointVariance > '10' && this.global.timeSpentToStoryPointVariance <= '20'){
return  '{ "background-color": "Gold"}';
}
else{ 
return '{ "background-color": "Crimson" }';
}

}

条件无法正常工作。我认为 '' 运算符无法正常工作,因为 IDE 显示 标志为红色,其余为蓝色,甚至 > 标志也为蓝色。

这里有什么问题?

【问题讨论】:

  • ngStyle 是一个元素的角度 attribute
  • 检查更新的答案
  • 你的意思是更新的问题
  • 顺便问一下,是什么让您将&lt;=string 一起使用?
  • 它应该可以工作了:)

标签: angular angular6


【解决方案1】:

ngStyle 必须在 div 内。在您的代码中,div 已关闭。请看下面:

<div [ngStyle]="{'background-color':global.timeSpent <= '10' ? 'LimeGreen' : ((global.timeSpent > '10' && global.timeSpent <= '20')  ? 'Gold' : 'Crimson' ) }">{{global.timeSpent}} </div>

【讨论】:

    【解决方案2】:

    您使用的引号过多。 global 是您组件中的变量吗?如果是这样,那么试试这个:

    [ngStyle]="{'background-color': global.timeSpent <= 0.1 ? 'LimeGreen' : ((global.timeSpentToStoryPointVariance > 0.1 && global.timeSpentToStoryPointVariance <= 0.2)  ? 'Gold' : 'Crimson' ) }"
    

    我将您的“10%”更改为 0.1,因为我假设您要比较的是数字而不是字符串。要点是你不应该将不是字符串的东西用引号括起来。

    不过,您绝对不应该在 html 中做所有这些事情。将其作为函数拉入您的组件中,然后像 [ngStyle]="getStyle()" 或类似的东西引用它。干净多了。

    【讨论】:

    • 什么是“global.timeSpent”?是数字吗?您不能将数字与带有“
    • 然后从中删除引号,它应该可以工作。这有意义吗?
    • 用墙壁撞头:'(为什么我把它作为字符串给出......谢谢:p
    【解决方案3】:

    因为 html 代码变得如此复杂。尝试将逻辑移至组件类

    get styleColor(){
    
      if(this.global.timeSpent <= '10%') return  '{ "background-color": "LimeGreen" }';
      if(this.global.timeSpentToStoryPointVariance > '10%' && this.global.timeSpentToStoryPointVariance <= '20%') return  '{ "background-color": "Gold"}';
      return '{ "background-color": "Crimson" }';
    }
    

    从样式中调用属性

    <div [ngStyle]="styleColor"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2019-07-07
      • 2016-07-02
      • 2018-11-04
      • 1970-01-01
      • 2017-10-02
      相关资源
      最近更新 更多