简体   繁体   English

在 *ngFor 中使用 ng-class 有条件地格式化 Angular 中的表格单元格 11

[英]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:一些东西:

  • CSS classes are usually not Capitalized. CSS 类通常不用大写。
  • You don't need to interpolate inside of ngClass.您不需要在 ngClass 内部进行插值。

    {'Pass': {{e.status}} =='Pass', 'Fail': {{e.status}} =='Fail'} <-- e.status not {{e.status}} {'通过':{{e.status}} =='通过','失败':{{e.status}} =='失败'} <- e.status 不是 {{e.status}}

  • I would stick to the usual [ngClass] (there are other ways to apply a dynamic class in Angular, but this is the most used).我会坚持使用通常的 [ngClass](还有其他方法可以在 Angular 中应用动态 class,但这是最常用的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM