Table of Contents
In this article, we will explore how to create a custom star rating component in Angular, which is commonly used for reviews on websites and applications. A well-designed star rating system enhances user experience by providing a simple and intuitive way for users to rate products or services.
Understanding the Basics of Angular Components
Angular components are the building blocks of any Angular application. They consist of a TypeScript class, an HTML template, and optional CSS styles. For a star rating component, we will create a reusable component that displays stars and captures user input.
Creating the Component
Use the Angular CLI to generate a new component:
ng generate component star-rating
Designing the Template
In the star-rating.component.html file, add the following code to display five stars:
<div class="star-rating">
<ng-container *ngFor="let star of stars; let index = index">
<span
class="star"
[class.filled]="index < rating"
(click)="setRating(index + 1)"
(mouseover)="hoverRating(index + 1)"
(mouseout)="resetHover()"
>★</span>
</ng-container>
</div>
Implementing the Logic in TypeScript
In the star-rating.component.ts file, define the component’s logic:
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 = 0;
stars: number[] = [1, 2, 3, 4, 5];
hoverRatingValue: number | null = null;
setRating(rating: number): void {
this.rating = rating;
}
hoverRating(rating: number): void {
this.hoverRatingValue = rating;
}
resetHover(): void {
this.hoverRatingValue = null;
}
}
Adding Styles for the Stars
In the star-rating.component.css file, add styles to display filled and empty stars:
.star {
font-size: 2rem;
color: #ccc;
cursor: pointer;
transition: color 0.2s;
}
.star.filled,
.star:hover,
.star:hover ~ .star {
color: #ffca28;
}
Integrating the Component into Your Application
Once the component is ready, include it in your parent component’s template:
<app-star-rating [(rating)]="userRating"></app-star-rating>
Bind the rating property to a variable in your parent component to capture user ratings.
Conclusion
Creating a custom star rating component in Angular involves designing the template, implementing the logic, and styling the stars for interactivity. This reusable component can enhance user engagement and provide clear feedback mechanisms on your site.