如何在html代码中添加多个三元操作符?



让我们考虑我有以下代码:它曾经应用css class到red4,但我需要应用css类到red11myData的size我想要那种有活力的大小。例如:大小将具有动态数字范围,0 - 20//0 - 100//0 - 10000等,颜色范围应取决于动态大小范围。

HTML:

<svg><path *ngFor="let item of myData" [attr.class]="item.myColor=='red1'?'red1':item.myColor=='red2'?'red2':item.myColor=='red3'?'red3':item.myColor=='red4'?'red4':null"></path>
</svg>
下面是我的css类:
svg path.red1 {
cursor: pointer;
fill: #ffcccc;
}
svg path.red2 {
cursor: pointer;
fill: #ffb3b3;
}
svg path.red3 {
cursor: pointer;
fill: #ff9999;
}
svg path.red4 {
cursor: pointer;
fill: #ff6666;
}
svg path.red5 {
cursor: pointer;
fill: #ff4d4d;
}
svg path.red6 {
cursor: pointer;
fill: #ff3333;
}
svg path.red7 {
cursor: pointer;
fill: #ff1a1a;
}
svg path.red8 {
cursor: pointer;
fill: #ff0000;
}
svg path.red9 {
cursor: pointer;
fill: #e60000;
}
svg path.red10 {
cursor: pointer;
fill: #cc0000;
}
svg path.red11 {
cursor: pointer;
fill: #b30000;
}

这是一个打字代码:

export interface DataInterface {
id: string;
title: string;
size: number;
myColor: string;
myCheck: string;
d: string;
class?: string;
}
myList = [{ "id": "SG-05", "size": 30, }, { "id": "SG-04", "size": 9, }, { "id": "SG-01", "size": 20, }];
myData: DataInterface[] = [
{
"id": "SG-01", "size": 20, "myColor": "default", "myCheck": 'false'
},
{
"id": "SG-02",  "size": 20, "myColor": "default", "myCheck": 'false', 
},
{
"id": "SG-03", "size": 20, "myColor": "default", "myCheck": 'false', 
},
{
"id": "SG-04",  "size": 40, "myColor": "default", "myCheck": 'false', 
},
{
"id": "SG-05",  "size": 70, "myColor": "default", "myCheck": 'false',
},
]
fillColor() {
for (let i = 0; i < this.myData.length; i++) {
let myCountry = this.myData[i].id;
for (let j = 0; j < this.myList.length; j++) {
if (myCountry === this.myList[j].id) {
this.myData[i].size = this.myList[j].size;
if (myCountry === this.myList[j].id && this.myList[j].size <= 0) {
this.myData[i].myColor = 'red1';
}
else if (myCountry === this.myList[j].id && this.myList[j].size <= 10) {
this.myData[i].myColor = 'red2';
}
else if (myCountry === this.myList[j].id && this.myList[j].size <= 20) {
this.myData[i].myColor = 'red3';
}
else if (myCountry === this.myList[j].id && this.myList[j].size <= 30) {
this.myData[i].myColor = 'red4';
}
}
}
console.log('$$$$$$$$$$2', this.myData);
}
}

任何帮助将不胜感激!谢谢你。

also

[ngClass]="item.myColor"

顺便说一句,你可以用

替换你的fillColor函数
this.myData.forEach((x:any)=>{
const country=this.myList.find(l=>l.id==x.id)
if (country)
{
x.size=country.size;
x.myColor='red'+(Math.floor(country.size/10)+1)
}
})

使用forEach和find数组方法

由于item.myColor返回颜色名称,您可以直接设置
[attr.class] = "item.myColor ? item.myColor : null"

最新更新