Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to style html with Angular 2

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 
like image 309
user172902 Avatar asked Feb 19 '26 20:02

user172902


1 Answers

<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 
like image 64
Günter Zöchbauer Avatar answered Feb 24 '26 00:02

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!