Search code examples
cssangularng-class

trying to use ngClass instead ngIf


I would rewrite this NgIf over ngClass for a shorter code. Unfortunately, the class is not accepted. Can the problem be solved?

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>

Solution

  • try this:

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