基于ngIf更改背景颜色

0lvr5msh  于 2022-10-04  发布在  Angular
关注(0)|答案(3)|浏览(472)

我有来自服务器数据库的值,并且我想根据将在视图上显示的ngIf来更改背景颜色,我该怎么做?

背景颜色会根据ngIF值进行更改。

<td>
          <div  *ngIf="obj.fruit ==3 "> Apple </div>
          <div  *ngIf="obj.fruit ==2 "> Orange </div>
          <div  *ngIf="obj.fruit ==1 "> Banana </div>
          <div  *ngIf="obj.fruit ==0 "> Cherries</div>
    </td>
xkrw2x1b

xkrw2x1b1#

这是我的建议

// FruitsType.ts
export enum FruitsType {
    Apple
    Orange
    Banana
    Cherries
}

// your.component.ts
fruitColors = new Map<FruitsType, {name: string, color: string}>([
    [FruitsType.Apple, {name: 'apple', color: 'red'}],
    [FruitsType.Orange, {name: 'orange', color: 'orange'}],
    [FruitsType.Banana, {name: 'banana', color: 'yellow'}],
    [FruitsType.Cherries, {name: 'cherries', color: 'purple'}]
]);

// your.component.html
<td [style.background-color]="fruitColors.get(obj.fruit).color">
   <div>{{fruitColors.get(obj.fruit).name}}</div>
</td>

此外,根据您的需要,可以将其转换为指令,这意味着您将能够重用指令,而无需在每个组件中编写所有这些逻辑。

eh57zj3b

eh57zj3b2#

test.component.ts中:

getColor(value) {
//return class
  if(value ==3) return 'b-blue'
  if(value ==2) return 'b-red'
}
getValue(value) {
  if(value ==3) return 'Apple'
  if(value ==2) return 'Orange'
}

test.component.html中:

<td [ngClass]="getColor(obj.fruit)">
   <div>{{getValue(obj.fruit)}}</div>
</td>
hkmswyz6

hkmswyz63#

下面是ngSwitch,它等同于ngIf:

<div [ngSwitch]="obj.fruit">
 <div *ngSwitchCase="'0'" style="background-color:red"> Apple </div>
 <div *ngSwitchCase="'1'"  style="background-color:orange"> Orange</div>
 <div *ngSwitchCase="'2'"  style="background-color:yellow"> Cherries</div>
 <div *ngSwitchDefault style="background-color:gray"> Pick again</div>
</div>

相关问题