Reputation: 3581
I have the following ngFor in my template
<span id="work-hour-span" *ngFor="let hour of hoursArray">{{hour}}</span>
What I want to achieve is to have different colour for this span based on the value of hour
For example,
if hour is between 0 and 2, the text color of hour is red,
if hour is between 2 and 4, the text color of hour is blue,
if hour is between 4 and 6, the text color of hour is green,
if hour is between 6 and 8, the text color of hour is yellow,
if hour is between 8 and 10, the text color of hour is purple,
if hour is between 10 and 12, the text color of hour is pink,
if hour is between 12 and 14, the text color of hour is grey,
The only way I can think of is have a whole log of ng-class which is very messy
[ngClass]="{redColor: hour < 2} [ngClass]="{blueColor: hour > 2 && hour < 4}...etc
Upvotes: 3
Views: 70
Reputation: 657338
<span [style.color]="getColor(hour)" id="work-hour-span" *ngFor="let hour of hoursArray">{{hour}}</span>
getColor(hour) {
switch(hour) {
case 0:
case 1:
return 'red';
case 2:
case 3:
return 'blue';
case 4:
case 5:
return 'green'
...
}
}
For performance reasons it would be better to move getColor()
to a pipe though
@Pipe({ name: 'hourColor' })
class HourColorPipe implements PipeTransform {
transform(hour:number) {
switch(hour) {
case 0:
case 1:
return 'red';
case 2:
case 3:
return 'blue';
case 4:
case 5:
return 'green'
...
}
}
}
<span [style.color]="hour | hourColor" id="work-hour-span" *ngFor="let hour
Upvotes: 2