I have 4 rows, each row contains 3 cards. I am fetching information for these cards from db then rendering them using ngfor in html. The problem is I want each of card of a row to show different color.
Example:->
ROW 1: BLUECARD | WHITECARD | REDCARD
ROW 2: BLUECARD | WHITECARD | REDCARD
as of now I able to do for two colors but how can I make it for 3 colors as I stated in example.
<div *ngFor="let r of rates; let i=index;">
<div [ngClass]="i % 2 == 0 ? 'BLUECARD' : 'REDCARD'">
<!-- card contents -->
</div>
</div>
As you can see I am able to show 2 colors alternatively but how can I show 3 colors instead?
CodePudding user response:
I would create an string array with your colors and then [ngClass]=colorArray[i]
or something similar.
CodePudding user response:
you can try these (meanwhile i am using silly logic for example only) :-
[ngClass]="{1 : 'BLUECARD', 2 : 'REDCARD', 3 : 'WHITECARD'}[i % 2]"
or
[ngClass]="{'BLUECARD': i % 2 === 0, 'REDCARD' : i % 2 !== 0, 'WHITECARD': i % 2 === undefined }"
CodePudding user response:
I had to do something like this I created a function that returns a color based on what you give it as a parameter; In your case, you can create a function that takes i as parameter and returns a color
<div [ngStyle]="{'background-color':giveCouleur(i)}">
<!-- card contents -->
</div>
In your ts file
giveCouleur(i:any){
var color="default_color";//or null if you want
if(i%2==0){
color="Your_colr";
//ex:color="#ffffff"
}else if(i%3==0){
color="your_color";
}else{
color="your_color"
}
//In this case, you can create as many conditions as you want.
return color;
}
you can try with ngClass
<div [ngClass]="{giveCouleur(i)}">
<!-- card contents -->
</div>
giveCouleur(i:any){
var color="default_color";//or null if you want
if(i%2==0){
color="BLUECARD";
}else if(i%3==0){
color="REDCARD";
}else{
color="WHITECARD"
}
//In this case, you can create as many conditions as you want.
return color;
}