尝试使用ngClass而不是ngIf

时间:2017-12-07 11:06:48

标签: css angular ng-class

我会在ngClass上重写这个NgIf以获得更短的代码。不幸的是,该课程不被接受。问题可以解决吗?

The long Version:   

 <div *ngIf="sp.outboundWeeks[i].status=='GREEN'">
                                        <div class="green">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>
                                    <div *ngIf="sp.outboundWeeks[i].status=='RED'">
                                        <div class="red">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>
                                    <div *ngIf="sp.outboundWeeks[i].status=='YELLOW'">
                                        <div class="yellow">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>

the short version should be like the code below:

[ngClass]="{'green':cw.status[i]=='GREEN','yellow':cw.status=='YELLOW','red':cw.status=='RED'}">{{cw.utilizationRate}}
     </div>

3 个答案:

答案 0 :(得分:1)

试试这个:

<div>
   <div [ngClass]="(sp.outboundWeeks[i].status=='GREEN') ? 'green' : 
         (sp.outboundWeeks[i].status=='RED') ? 'red' : 'yellow'">
      {{sp.outboundWeeks[i].utilizationRate}}
   </div>
</div>

答案 1 :(得分:1)

我假设你的对象是:

    sp = {
    outboundWeeks: [{
      status: 'GREEN',
      utilizationRate: 'das',
    }],
  };
  cw = {
    status: ['GREEN'],
    utilizationRate: 'sad',
  };

因此模板应该类似于

<div *ngIf="sp.outboundWeeks[0].status =='GREEN'">
      <div class="green">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>
    <div *ngIf="sp.outboundWeeks[0].status=='RED'">
      <div class="red">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>
    <div *ngIf="sp.outboundWeeks[0].status=='YELLOW'">
      <div class="yellow">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>

    //SHORT HAND
    <div [ngClass]="{'green': cw.status[0] === 'GREEN', 'yellow': cw.status[0] === 'YELLOW','red': cw.status[0] === 'RED'}">
      {{ cw.utilizationRate }}
    </div>

我猜您的迭代不正确,因为短版本与您引入的较长版本略有不同,但是,我添加了一个示例对象来向您展示它应该如何工作。

更好的解决方案可能是创建一个@Pipe来返回正确的类。它应该更清洁,更快。

类似

 <div [ngClass]="status | yourPipe">
      {{ cw.utilizationRate }}
 </div>

答案 2 :(得分:0)

Abdul Rafay解决方案很好,我的解决方案在我看来更明确和可读:)

<div>
   <div [class.green]=" sp.outboundWeeks[i].status=='GREEN' "
        [class.red]=" sp.outboundWeeks[i].status=='RED' "
        [class.yellow]=" sp.outboundWeeks[i].status=='YELLOW' ">
      {{sp.outboundWeeks[i].utilizationRate}}
   </div>
</div>