Star Rating in Angular
Star rating is a common feature in many applications, allowing users to rate products, services, or content. Half star ratings offer a more nuanced option, allowing for fractional ratings in addition to whole numbers. In this blog, we’ll go over how to implement a half-star rating system in Angular.
Star rating is a common feature in many applications, allowing users to rate products, services, or content. Half star ratings offer a more nuanced option, allowing for fractional ratings in addition to whole numbers. In this blog, we’ll go over how to implement a half-star rating system in Angular.
- Installation
To get started, we’ll need to install the Angular CLI if you don’t already have it installed. You can do this by running the following command in your terminal:
npm install -g @angular/cli
Next, create a new Angular project by running:
ng new my-app
- Component
Create a new component for the star rating by running the following command in your terminal:
ng g c star-rating
- Template
In the template file star-rating.component.html
, add the following code to display the stars:
<div class="star-rating">
<i class="fa fa-star" *ngFor="let star of stars"></i>
<i class="fa fa-star-half" *ngIf="rating % 1 !== 0"></i>
</div>
In this template, we use ngFor
to loop over an array of stars, displaying a full star for each whole number in the rating. If the rating is not a whole number, we display a half star using ngIf
.
- Style
Next, let’s add some basic styles for the stars in the star-rating.component.css
file:
.star-rating {
font-size: 2em;
color: #ffc107;
}
- Component Class
In the component class star-rating.component.ts
, let's add a property to store the rating, and a getter to calculate the number of stars to display:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-star-rating',
templateUrl: './star-rating.component.html',
styleUrls: ['./star-rating.component.css']
})
export class StarRatingComponent {
@Input() rating: number; get stars() {
return Array(Math.floor(this.rating)).fill(0);
}
}
- Usage
Finally, to use the star rating component in another component, simply add the following code to the template file:
<app-star-rating [rating]="3.5"></app-star-rating>
Here, we pass in a rating of 3.5 to the star rating component, which will display 3 full stars and a half star.
And that’s it! With these steps, you now have a working half-star rating system in Angular. You can customize the design and functionality further as needed for your specific use case.
Note: In the code above, we used Font Awesome for the star icons. You can use any icons of your choice or create your own custom icons.