【问题标题】:style binding dynamic, 4 different color样式绑定动态,4种不同颜色
【发布时间】:2023-03-12 09:01:01
【问题描述】:
我想这样设置我的表格:
我试试这个代码,但有 2 种颜色。
<table *ngFor="let item of notif">
<tr class="cell" [style.border-color]="item.alarmnr === 1 ? 'green' : 'red' ">
</tr>
</table>
但我需要 4 种或更多颜色。
我有 4 个报警号码,
alarmnr = 1 --> red
alarmnr = 2 --> blue
alarmnr = 3 --> yellow
alarmnr = 4 --> green
如何实施?你能给我建议吗?
谢谢
【问题讨论】:
标签:
html
angular
typescript
data-binding
【解决方案1】:
尝试为此使用 ngClass
<table *ngFor="let item of notif">
<tr class="cell" [ngClass]="{'red': item.alarmnr === 1,
'blue': item.alarmnr === 2,
'yellow': item.alarmnr === 3,
'green' : item.alarmnr === 4}">
</tr>
</table
【解决方案2】:
我建议您在组件中执行类似这样的功能:
getColorByAlarmnr(alarmnr: number) : string {
switch(alarmnr){
case 1 : return 'red';
case 2 : return 'blue';
case 3 : return 'yellow';
case 4 : return 'green'
}
}
在 html 中:
<table *ngFor="let item of notif">
<tr class="cell" [style.border-color]="getColorByAlarmnr(item.alarmnr)">
</tr>
</table>
或者您可以使用正确颜色的键、值对来定义对象/映射:
let colors = {
1:'red'
2:'blue'
3:'yellow',
4:'green'
}
在 html 中:
<table *ngFor="let item of notif">
<tr class="cell" [style.border-color]="colors[item.alarmnr]">
</tr>
</table>
【解决方案3】:
是的,你可以在 ts 文件中创建一个函数
并将逻辑上的类或样式返回给变量并使用该变量
给[style.border-color] ="yourvariable"