Build Star Rating using NgBootstrap

In this article, we’ll learn how to create a star rating using NgBootstrap in Angular. For that, we used the “ng-bootstrap/ng-bootstrap” module. Let’s create a new project to implement a star rating in angular for that you need to run the following command to create a project.

ng new star-rating-demo

“star-rating-demo” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go to their directory. For example “cd star-rating-demo”. To Run angular applications, it required to run “ng serve”.
After that, we need to install the ng-bootstrap/ng-bootstrap npm package in our application. run below command to install.

ng add @ng-bootstrap/ng-bootstrap

NgbModule need to imported app module and registered in “app.module.ts” file.

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";

import { AppComponent } from "./app.component";
import { HelloComponent } from "./hello.component";

import { NgbModule } from "@ng-bootstrap/ng-bootstrap";

  imports: [BrowserModule, FormsModule, NgbModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent]
export class AppModule {}

After adding the module you can use it in our component. Let’s add the below code in our app.component.ts file.

import { Component, VERSION } from "@angular/core";

  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
export class AppComponent {
  name = "Angular " + VERSION.major;

  starRating = 0;
  currentRate = 3.14;

below code need to “app.component.html” file.

<h2>Star Rating Example</h2>

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


<h2>Custom rating Display</h2>

<ng-template #heart let-fill="fill">
	<span class="star" [class.full]="fill === 100">
    <span class="half" [style.width.%]="fill">&hearts;</span>&hearts;

<ngb-rating [(rate)]="currentRate" [starTemplate]="heart" [readonly]="true" [max]="5"></ngb-rating>

<pre>Rate: <b>{{currentRate}}</b></pre>
<button class="btn btn-sm btn-outline-primary mr-2" (click)="currentRate = 2.5">2.5</button>
<button class="btn btn-sm btn-outline-primary mr-2" (click)="currentRate = 1.53">1.53</button>
<button class="btn btn-sm btn-outline-primary mr-2" (click)="currentRate = 4.25">4.25</button>
<button class="btn btn-sm btn-outline-primary mr-2" (click)="currentRate = 2.75">2.75</button>


Below is the full embeded code for the star rating angular. you can easily used in your application.

Spread the love