尝试使用 ngClass 而不是 ngIf

trying to use ngClass instead ngIf

我会通过 ngClass 重写这个 NgIf 以获得更短的代码。不幸的是,class 不被接受。问题能解决吗?

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>

试试这个:

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

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>

我假设你的对象是这样的:

    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,其中 returns 适合您 class。它应该更干净、更快。

类似于

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