Deeriss
Deeriss

Reputation: 23

Angular - Display rating value as stars

I have a rating functionality that assigns a rating to a product. What I want to do is to display the average of all rating values for one product on that product's page. I already have the average value calculated for each product, but I don't know how to display the value as the number of stars. The thing is that this value is type float.

This is where I give a rating:

HTML file

<ng-container *ngFor="let rateVal of [5, 4, 3, 2, 1]">
    <input (click)="rateProduct(rateVal)" [id]="'star'+rateVal" [value]="rateVal-0.5" name="rating" type="radio" />
    <label class="full" [for]="'star'+rateVal"></label>
    <input (click)="rateProduct(rateVal-0.5)" [value]="rateVal-0.5" [id]="'halfstar'+rateVal" name="rating" type="radio" />
    <label class="half" [for]="'halfstar'+rateVal"></label>
</ng-container>

Do you have any idea how I can display the average value as stars?

Upvotes: 0

Views: 4382

Answers (1)

Yong Shun
Yong Shun

Reputation: 51295

You can display star rating by calculating the width as formula below:

Full width: 75 (in px)

Max star rating: 5 (star)

Width: (rate * Full width) / Max star rating


SOLUTION

Pre-requisites: Install these packages

npm install bootstrap
npm install font-awesome

Step 1: Import these css files to global css

style.css

@import "bootstrap/dist/css/bootstrap.min.css";
@import "font-awesome/css/font-awesome.min.css";

Step 2: Add rating logic

rate.component.ts

export class RateComponent  {
  starWidth: number = 0;

  rateProduct(rateValue: number) {
    this.starWidth = rateValue * 75 / 5;
  }
}

Step 3: Add .crop style (Parent div hide child div for not overflown when child div has longer width than parent div)

star.component.css

.crop {
  overflow: hidden;
}

Step 4: Show stars for rating

rate.component.html

<ng-container *ngFor="let rateVal of [5, 4, 3, 2, 1]">
  <input (click)="rateProduct(rateVal)" [id]="'star'+rateVal" [value]="rateVal-0.5" name="rating" type="radio" />
  <label class="full" [for]="'star'+rateVal"></label>
  <input (click)="rateProduct(rateVal-0.5)" [value]="rateVal-0.5" [id]="'halfstar'+rateVal" name="rating" type="radio" />
  <label class="half" [for]="'halfstar'+rateVal"></label>
</ng-container>

<hr/>

<div class="crop"
     [style.width.px]="starWidth">
  <div style="width: 75px">
    <span class="fa fa-star"></span>
    <span class="fa fa-star"></span>
    <span class="fa fa-star"></span>
    <span class="fa fa-star"></span>
    <span class="fa fa-star"></span>
  </div>
</div>

Sample solution in StackBlitz

Upvotes: 4

Related Questions