2017-06-15 57 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虽然我更新列表,感谢提出了.. –