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? Component:
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.
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.
Improved version
In this solution, even on hover all previous stars' colors will change to yellow:
HTML:
<div class="row">
<div class="col-sm-12">
<ul class="list-inline rating-list" *ngFor="let star of stars; let i= index" style="display: inline-block">
<li (click)="countStar(star)" id="{{'starId'+i}}" [ngClass]="{'selected': (star <= selectedValue)}"
(mouseover)="addClass(star)" (mouseout)="removeClass(star)"> ★
</li>
</ul>
</div>
</div>
Component.ts:
stars: number[] = [1, 2, 3, 4, 5];
selectedValue: number = 0;
countStar(star) {
this.selectedValue = star;
}
addClass(star) {
let ab = "";
for (let i = 0; i < star; i++) {
ab = "starId" + i;
document.getElementById(ab).classList.add("selected");
}
}
removeClass(star) {
let ab = "";
for (let i = star-1; i >= this.selectedValue; i--) {
ab = "starId" + i;
document.getElementById(ab).classList.remove("selected");
}
}
SCSS:
.rating-list {
li {
font-size: 20px;
float: right;
color: #ddd;
padding: 10px 5px;
&:hover {
color: #ffd700;
~ {
li {
color: #ffd700;
}
}
}
}
li.selected {
color: #ffd700;
}
display: inline-block;
list-style: none;
}
See this example for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With