问题描述
我正在通过使用 *ngFor 循环遍历数组的内容来填充表的内容。
表格填充得很好,但我想根据填充的值更改单元格的背景(例如,如果值为“通过”则为绿色,如果值为“失败”则为红色。
我采用的方法是使用 ng-class 来评估数组元素值的内容并使用它来设置背景 - 但它不起作用。
组件 HTML
<tr *ngFor="let e of list;">
<td>{{ e.description}}</td>
<td ng-class="{'Pass' : {{e.status}} =='Pass','Fail' : {{e.status}} =='Fail'}">{{ e.status }}
</td></tr>
组件 CSS
.Pass {
background-color: green;
}
.Fail {
background-color: red;
}
解决方法
解决方案:
<tr *ngFor="let e of list;">
<td>{{e.description}}</td>
<td [ngClass]="{Pass: e.status === 'Pass',Fail: e.status === 'Fail'}">{{e.status}}
</td>
</tr>
或者如果状态可以是通过或失败 - 我们可以使用三元运算符检查一次条件:
[ngClass]="e.status=== 'Pass'? 'Pass' : 'Fail'"
一些事情:
- CSS 类通常不大写。
- 您不需要在 ngClass 内部进行插值。
{'Pass' : {{e.status}} =='Pass','Fail' : {{e.status}} =='Fail'}
- 我会坚持使用通常的 [ngClass](还有其他方法可以在 Angular 中应用动态类,但这是最常用的)。