【问题标题】:Change color of text in td based on value in Angular 6根据Angular 6中的值更改td中文本的颜色
【发布时间】:2019-08-24 23:43:54
【问题描述】:

我的表格中有一个状态列 我需要根据值显示不同颜色的文本。我正在使用 Angular 6。

<table>
<th>Status</th>
<th>Name</th>
<tr *ngFor="let data of data >
<td>{{data.status}}</td>
<td>{{data.name}}</td>
</tr>
</table>

如果状态为 Pass and Approved,则文本为绿色, 如果状态为失败和错误,则文本为红色, 如果状态为警告,则文本为黄色, 如果状态为 Ignored,则文本为蓝色,

谁能帮我在Angular 6中做到这一点。

【问题讨论】:

标签: css angular6


【解决方案1】:

首先,你可以为对应的颜色实例化一个数组:

打字稿:

colors = [{ status: "Passed", color: "red" }, { status: "Approuved", color: "red" }, 
                { status: "warning", color: "green" }, { status: "Ignored", color: "yellow" }]

那么就可以使用ngStyle来动态设置样式了:

HTML

...
<tr *ngFor="let row of data" [ngStyle]="{'background':getColor(row.status)}">
...
</tr>

getColor 方法如下:

打字稿

getTheColor(status) {
       return this.colors.filter(item => item.status === status)[0].color 
       // could be better written, but you get the idea
}

根据状态从对应的颜色数组返回颜色值

就是这样

Demo

【讨论】:

  • 谢谢。这就是我一直在寻找的。 @维加
  • 非常好,我把它改成了return this.colors.filter(item =&gt; item.status === status)[0]?.color ?? 'black' ,它非常适合我的用例:)
猜你喜欢
  • 2021-03-30
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 2021-11-14
  • 1970-01-01
  • 2019-09-17
相关资源
最近更新 更多