2017-06-15 62 views
1

我有一個疑問,我不知道如何解決。我從服務器帶來一些數據並將其顯示在一張桌子上。其中一個字段是一個字符串,其值爲'OK','ERROR'或'CANCEL'。有可能根據值分配一些引導類?例如bg-succes,如果'OK'或bg-danger如果'CANCEL'。Angular 2 - 設置自舉類取決於字符串值

例子:

<table class="table table-hover"> 
    <thead class="thead-inverse"> 
     <tr> 
      <th class="text-center"><strong>Date 1/ Date 2</strong></th> 
      <th class="text-center"><strong>Status</strong></th> 
      <th class="text-center"><strong>Date 3</strong></th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr *ngFor="let item of items"> 
      <td class="text-center"> 
       <tr class="text-center"> {{item.Date1}} </tr> 
       <tr class="text-center"> {{item.Date2}} </tr> 
      </td> 
      <td class="text-center"> 
       <tr>Status</tr> 
       <tr class="bg-success"> {{item.Status}}</tr>//Want to assign here the class     
      </td> 
      <td class="text-center"> {{item.Date3}} </td>    
     </tr> 
    </tbody> 
</table> 

順便感謝!

回答

2

使用ngClass指令可以達到相同效果。

<tr [ngClass]="getStatusClass(item.Status)"> {{item.Status}}</tr> 

代碼

getStatusClass(status: string){ 
    let statuses = {"OK": "bg-success", "ERROR": "bg-danger", "CANCEL": "bg-warning"} 
    return statuses[status] || 'bg-default'; 
} 
+1

不過要小心,角是區分大小寫的。你的密鑰應該是OK,ERROR和CANCEL,不好,錯誤和取消。 – trichetriche

+0

工作正常!但只是數組的第一個元素。其他人不採取任何類:/ – Aw3same

+1

@trichetriche不是關於Angular,在這種情況下字典鍵是區分大小寫:p雖然我更新列表,感謝提出了.. –