Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

angular - How to change color of the rating star using ngClass

I am using RatingModule from 'ngx-bootstrap'. Initially the star color should be black.When I choose 1 star then the star color should be red 2 Stars -Blue 3 Stars-Yellow 4 Stars -pink 5 Stars-Green I don't how to achieve this using ngClass.The below code is not working.I have initialized the ratingValue as 0

  max=5;//Five stars will be displayed
     <rating formControlName="ratingValue" [max]="max" ></rating>

I added this ngClass in above but it didn't work.

[ngClass]="{'black':ratingValue==0,'red':ratingValue==1,'red':ratingValue==2,'red':ratingValue==3,'red':ratingValue==4,'red':ratingValue==5}"

.pink{
color:pink;
}
.red{
color:red;
}
.yellow{
color:yellow;
}
.blue{
color:blue;
}
.green{
color:green;
}
.black{
color:black;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

you probably need to access ratingValue.value to get the current value of the formControl.

Then use ngClass like you did in your example:

[ngClass]="{'black':ratingValue==0,'red':ratingValue==1,'blue':ratingValue==2,'yellow':ratingValue==3,'pink':ratingValue==4,'green':ratingValue==5}">

or even better (looks cleaner) pass a function to the ts file:

[ngClass]="getStarColorCSSClass(ratingValue.value)"

and in the TS file:

  getStarColorCSSClass(value: number): string {
    switch(value) {
      case 0:
        return 'black';
      case 1:
        return 'red';
      case 2:
        return 'blue';
      case 3:
        return 'yellow'
      case 4:
        return 'pink';
      default:
        return 'green';
    }
  }
}

If your CSS classes are only created for setting the 'color' property, we can also avoid to create them by using ngStyle instead of ngClass (with the function above):

[ngStyle]="{color: getStarColorCSSClass(ratingValue.value)}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...