【问题标题】:Angular 2 or 4 or 5 ng-style with more than 2 conditional outputsAngular 2 或 4 或 5 ng 样式,具有超过 2 个条件输出
【发布时间】:2018-04-30 10:15:06
【问题描述】:

像 angularjs 1.x 如何实现 ngstyle 超过 2 个条件?

Angularjs 1.x:

<div ng-controller="MyCtrl">
 <p ng-style="cond1  ? { color:'green' } : cond2 ? {color: 'blue'} : cond3 ? {color: 'red'} : {color: ''}">Hello World!</p>
</div>

Angular-2/4/5: 在下面的代码中,黑色、金色和绿色是打字稿中声明的变量。

<button class="button" id="btn_status" [ngStyle]="darked?     {backgroundColor:'darked'} : gold?{backgroundColor:'gold'} : green?{backgroundColor:'green'}">

这里出现错误,

【问题讨论】:

  • [ngStyle]="{'color':cond1?'green':cond2?'blue':cond3?'red':''}" (" 之间的所有引号都是单引号)
  • 或 [style.color]="cond1?'green':cond2?'blue':cond3?'red':''" (只有第一个和最后一个是双引号)

标签: angular angular5 angular2-template


【解决方案1】:

你也可以这样做:

<button class="button" id="btn_status" [ngStyle]="{'backgroundColor': darked || gold || green}">

组件:

darked = null;
gold = null;
green = null;

cond1() {
  if(true) 
    this.darked = 'black'
}

【讨论】:

    【解决方案2】:

    如果你想要这样的东西,你最好调用一个方法。如果可能的话,您希望避免将大量逻辑放入模板中:

    <button
      class="button"
      id="connection_status"
      [ngStyle]="colorCheck()">
    

    然后该方法返回您需要的颜色。

    colorCheck() {
      if (this.darked) {
        return {backgroundColor: 'darked'};
      }
    }
    

    甚至更好,因为它们都是您设置的同一类:

    <button
      class="button"
      id="connection_status"
      [style.backgroundColor]="colorCheck()">
    
    colorCheck() {
      if (this.green) {
        return 'green';
      }
      // etc
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多