How to Build Star Rating in Angular 10 Application

Last updated on by Digamber

This comprehensive tutorial answers you about creating a star rating system in Angular 10 using the NgBootstrap library.

NgBootstrap is a package for bootstrap; it doesn’t require 3rd party JavaScript. Most importantly, the Angular widgets are assimilated from the ground only using Bootstrap 4 CSS and some APIs, especially for the Angular ecosystem.

In this tutorial, we will build a 5-star rating system, i am sure you must have seen the star rating system before. Typically star rating system is used in e-commerce sites where a user rates from 1 star to 5 stars to the services or products.

Without further ado, let’s build a star rating component using the latest Angular 10 and NgBootstrap library.

Create Angular Application

Install Angular CLI with the following command, skip this step if angular CLI already installed

npm install -g @angular/cli

Create an Angular application to display the Angular star rating demo.

ng new angular-star-rating-example

Navigate to the project root:

cd angular-star-rating-example

Install Marked Parser Package

Install the marked Markdown parser plugin through NPM. Its a low-level and powerful compiler for parsing Markdown without caching or blocking for long periods.

npm i marked

Install NGBootstrap in Angular

You just need to run the given below command to install the ng-bootstrap package.

ng add @ng-bootstrap/ng-bootstrap

We have installed the ng-bootstrap library for the default application designated in angular.json file.

Create Star Rating in Angular

The ng-bootstrap library amplifies the bootstrap support and comes with robust components. Out of one, we are going to use NgbRating to build a star rating system in Angular.

NgbRating directive helps visualising and interacting with a star rating bar.

Head over to app.component.html file and define the NgbRating directive.

<h2>Angular 10 Star Rating Example</h2>

<ngb-rating [max]="5" [(rate)]="starRating" [readonly]="false"></ngb-rating>

The max property sets the maximum number of ratings, and [(rate)] input configures the current rating. Even the decimal value, such as 2.50, could be set up.

Add code in app.component.ts file

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {

  starRating = 0; 

}

Let’s style the rating component:

ngb-rating {
    color: #FFC107;
    font-size: 80px;
}

Run the application.

ng serve --open

Build Star Rating in Angular

Summary

This quick tutorial helped us understand the easy method to build a star rating in Angular using ng-bootstrap. I hope you liked it; please share this tutorial with others.