【问题标题】:CSS td conditional background color settingCSS td 条件背景色设置
【发布时间】:2020-06-12 16:03:23
【问题描述】:
假设我有以下角度表
<table>
<tr *ngFor="let company of investTable; let i = index">
<td>
{{company.name}}
</td>
<td>
{{company.price}}
</td>
<td>
{{company.profit}}
</td>
</tr>
</table>
如何制定一个简洁的解决方案,让表格单元格根据单元格值具有背景颜色?可以说,如果公司利润为正,则将其设为绿色。
【问题讨论】:
标签:
css
angular
html-table
conditional-statements
background-color
【解决方案1】:
在css中
td.highlight {
background-color: green;
}
在 html 中:-
<table>
<tr *ngFor="let company of investTable; let i = index">
<td>
{{company.price}}
</td>
<td [ngClass]="{'highlight': company.profit > 0}">
{{company.profit}}
</td>
</tr>
</table>
【解决方案2】:
您可以将其添加到您的 html 中:
<td [style.positive]="company.profit > 0">
这是你的CSS:
td.positive{
background-color: green;
}
【解决方案3】:
查看ngStyle 和ngClass。最简单的用例是直接绑定到 style 属性。
<table>
<tr *ngFor="let company of investTable; let i = index">
<td>
{{company.name}}
</td>
<td>
{{company.price}}
</td>
<td [style.background-color]="company?.profit > 5 ? 'green' : 'red'">
{{company.profit}}
</td>
</tr>
</table>