Scorpion_beardo
Scorpion_beardo

Reputation: 45

Change Color of every element dynamically in Star Rating

I have implemented star rating and it works well. Now requirement is to have different color for each star where in my star color comes from CSS and its colored as GOLD. How can I give it different colors. for example - 1st star should be red, second blue, third green and so on..

<fieldset class="rating">
    <ng-container *ngFor="let star of starList">
        <input type="radio" id="th {{star.id}} {{j}}" name="th_{{j}}" (click)="updateRating(star.value,kpi.kpiId)" />
        <label [class]="star.class" for="th {{star.id}} {{j}}" [title]="star.value"></label>
    </ng-container>
</fieldset>

Css:

.rating {
    border: none;
    float: left;
    direction: ltr;
}

.rating>input {
    display: none;
}

.rating>label:before {
    margin: 5px;
    font-size: 1.25em;
    font-family: "Font Awesome 5 Free";
    display: inline-block;
    content: "\f005";
    font-weight: 900;
}

.rating>.half:before {
    content: "\f089";
    position: absolute;
}

.rating>label {
    color: #ddd;
    float: right;
}

.rating>input:checked~label,

/* show gold star when clicked */  

.rating:not(:checked)>label:hover,

/* hover current star */ 

.rating:not(:checked)>label:hover~label {
    color: gold;
    cursor: pointer;
}

Upvotes: 3

Views: 1836

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

this an example how you can achieve this simply create a class for each stage from 1 star to 5 star

.rate-1 label:nth-child(1){
  background: red;  
}

.rate-2 label:nth-child(1) ,.rate-2 label:nth-child(2){
  background: orange;  
}

.rate-3 label:nth-child(1) ,.rate-3 label:nth-child(2) , .rate-3 label:nth-child(3){
  background: blue;  
}

.rate-4 label:nth-child(1) , .rate-4 label:nth-child(2) , .rate-4 label:nth-child(3) ,.rate-4 label:nth-child(4){
  background: yellow;  
}


.rate-5 label:nth-child(1) , .rate-5 label:nth-child(2) , .rate-5 label:nth-child(3) , .rate-5 label:nth-child(4) , .rate-5 label:nth-child(5){
  background: green;  
}

template

<fieldset class="rating" [attr.class]="'rate-'+selectedValue">
    <ng-container *ngFor="let star of starList" >
        <label>
           <input type="radio" [value]="star" (click)="updateValue(star)"/> ★
        </label>
    </ng-container>
</fieldset>


{{selectedValue}}

stackblitz demo 🚀🚀

Upvotes: 1

MKJ
MKJ

Reputation: 120

check below code may be it will help you :

.yellow{
  color:yellow
}
.purple{
  color:purple
}
.blue{
  color:blue
}
.green{
  color:green
}
<div [ngClass] = "noOfStars==1 ?'yellow':noOfStars==2?'purple':noOfStars==3?'blue':noOfStars==4?'green'"></div>

Upvotes: 0

Related Questions