AAaaAA
AAaaAA

Reputation: 85

change background color based on ngIf

I have values coming from the server database, and I want to change the background color based on which ngIf will appear on the view, how do I do that.?

the background color changes based on the ngIF value ..

    <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>

Upvotes: 1

Views: 1972

Answers (3)

Pantelis Firestorm
Pantelis Firestorm

Reputation: 1

here it is with ngSwitch, which is equivelent to 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>

Upvotes: 0

WSD
WSD

Reputation: 3587

Here's my suggestion

// 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>

Also, depending on your needs this can be transformed into a Directive, meaning that you'll be able to reuse the directive without writing all this logic in each component.

Upvotes: 3

MohammadReza Abbasi
MohammadReza Abbasi

Reputation: 500

in 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'
}

in test.component.html:

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

Upvotes: 1

Related Questions