[英]Using ng-class within *ngFor to conditionally format table cell in Angular 11
I'm taking populating the contents of a table by using *ngFor to cycle through the contents of an array.我正在通过使用 *ngFor 循环遍历数组的内容来填充表的内容。
The table populates just fine, but I want to change the background of a cell based on the value it has been populated with (for example green if the value is "pass" and red if the value is "fail."该表填充得很好,但我想根据它填充的值更改单元格的背景(例如,如果值为“通过”则为绿色,如果值为“失败”则为红色。
The approach I'm taking is to use ng-class to evaluate the content of the value of element of the array and using that to set the background - but it's not working.我采用的方法是使用 ng-class 评估数组元素值的内容并使用它来设置背景 - 但它不起作用。
Component HTML组件 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>
Component CSS组件 CSS
.Pass {
background-color: green;
}
.Fail {
background-color: red;
}
Solution:解决方案:
<tr *ngFor="let e of list;">
<td>{{e.description}}</td>
<td [ngClass]="{Pass: e.status === 'Pass', Fail: e.status === 'Fail'}">{{e.status}}
</td>
</tr>
Or if the status can be either pass or fail - we can check the condition once with the ternary operator:或者,如果状态可以是通过或失败——我们可以使用三元运算符检查一次条件:
[ngClass]="e.status=== 'Pass'? 'Pass' : 'Fail'"
A few things:一些东西:
{'Pass': {{e.status}} =='Pass', 'Fail': {{e.status}} =='Fail'} <-- e.status not {{e.status}} {'通过':{{e.status}} =='通过','失败':{{e.status}} =='失败'} <- e.status 不是 {{e.status}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.