Angular: star rating

Issue

I would like implement rating star system. After click returns correct value of star. I have a problem with correctly displaying the selected stars. Just like in this picture, it doesn’t show me 3 stars in yellow. How to change it? rating starComponent:

 export class RatingStarComponent implements OnInit {
  stars: number[] = [1, 2, 3, 4, 5];
  constructor() { }
  ngOnInit() {
  }
  countStar(star) {
    console.log('Value of star', star);
  }
}

HTML:

 <div class="row">
  <div class="col-sm-12">
      <ul class="list-inline rating-list" *ngFor="let star of stars" style="display: inline-block" >
          <li (click)="countStar(star)"><i   class="fa fa-star "></i></li> 
      </ul>
  </div>
</div>

CSS:

  .rating-list li {
  float: right;
  color: #ddd;
  padding: 10px 5px;

}

.rating-list li:hover,
.rating-list li:hover ~ li {
  color: #ffd700;
}

.rating-list {
  display: inline-block;
  list-style: none;
}

Any help or suggestion is welcome.

Solution

You have to store the selected value:

countStar(star) {
    this.selectedValue = star;
    console.log('Value of star', star);
}

And add class which will change color of the star for all the stars with less or equal rating:

.rating-list li.selected {
    color: #ffd700;
}
<li (click)="countStar(star)"
    [ngClass]="{'selected': (star <= selectedValue)}">
        <i class="fa fa-star"></i>
</li> 

See full example for the details.

Answered By – Sergey Mell

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published