Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Different ways of adding Angular star rating component.

Angular star rating

We can easily implement the Angular start rating component it has a value range from (usually 1–5), with the highest number of stars indicating the best quality, the lowest value indicating low quality.

We have few objectives in this tutorial, but three main objectives are as follow.

  1. Best available Angular Star rating libraries .
  2. Star rating example using bootstrap, ngx-star-rating, ngx-material-rating
  3. Create our own custom star rating component

Best star rating libraries in Angular.

There are plenty of third parties libraries to implement Angular star rating libraries. We’ll list here some, you can select based on your requirement.

NameDescription
ngx-star-ratingSimple Angular rating control from angular2 application using font awesome icon. It has a weekly download of 1,350 and a size of about 464.4 kB.
ngx-bootstrapThe ngx-bootstrap rating component, used if you’re using Bootstrap as a UI library for the angular projects.
ng-bootstrapThe ng-bootstrap rating component, used if you’re using Bootstrap as a UI library for the angular projects.
ngx-material-ratingThe ngx-material-rating, for material design.
custom material ratingCreating our own custom material rating
Angular star rating libraries

Angular star rating component from ngx-bootstrap rating component

Let demonstrate the Angular star rating component from the ngx-bootstrap, for Angular bootstrap, we can either use ngx-bootstrap or ng-bootstrap library. Let use the ngx-bootstrap library and create an Angular project.

ng new bootstrapRatingApp
cd bootstrapRatingApp
ng add ngx-bootstrap

The steps of installing Bootstrap using ng-bootstrap.

  1. Create Angular project to used Bootstrap component in Angular.
  2. Install or add ngx-bootstrap in Angular project.
  3. Add individual component module inside the app.module.ts file.
  4. Add Bootstrap CSS 4 CDN in index.html in Angular project.
  5. Used Bootstrap component in Angular project.

We need to add Bootstrap CSS CDN in index.html, let’s do it.

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>BootstrapApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"
    integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
</head>

<body>
  <app-root></app-root>
</body>

</html>

We need to add RatingModule from ngx-bootstrap in our angular project app.module.ts file. Also import formsModule also.

....
import { RatingModule } from 'ngx-bootstrap/rating';
import { FormsModule } from '@angular/forms';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ....
    FormsModule,
    RatingModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Angular bootstrap rating component
Angular bootstrap rating component

Let add an Angular Bootstrap rating component tag inside our component template.

<rating  style="color: #0275d8;font-size: 40px;" [(ngModel)]="rate" [max]="max" [readonly]="isReadonly">
</rating>

<div class="card">
  <pre class="card-block card-header" style="margin:15px 0;">
    Rate: <b>{{rate}}</b>
  </pre>
</div>

Define rating attribute value inside component typescript file.

  max = 5;
  rate = 2;
  isReadonly = false;

Angular star rating example 3 using ngx-star-rating

We’ll demonstrate ngx star rating example using third-party library the ngx-star-rating. Here we first need to install this library in our project by following the command.

ng new starRatingApp
cd starRatingApp
npm i ngx-star-rating --save

Here is a screenshot of our first example of the ngx star rating example.

ngx star rating example
ngx star rating example

Once we had installed the ngx-star-rating library, we need to add font awesome CSS CDN in index.html in our Angular project

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

We also need to import NgxStarRatingModule in the app.module.ts file as follows.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgxStarRatingModule } from 'ngx-star-rating';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgxStarRatingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Let create an Angular reactive form to add a rating component, let edit the app.component.ts file

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {

    this.form = this.fb.group({
      rating: ['', Validators.required],
    })
  }
}
<form [formGroup]="form">
  <ngx-star-rating formControlName="rating" [id]="'rating'"></ngx-star-rating>
  <div>Rating: {{form.value.rating}}</div>
  <p>form is valid: {{ form.valid ? 'true' : 'false' }}</p>
</form>

Creating our own custom star rating

Let’s create an angular start rating component for material design, you can create the same start rating component without using any UI library. I have taken this example from https://stackblitz.com/edit/angular-material-star-rating? This example was made in Angular version 5. Let implement this example in Angular 13 latest. First, we need to create an Angular project and add Angular material.

ng new customRating
cd customRating
ng add @angular/material

Let create a custom rating component, by running the following command.

ng generate component components/rating

In our custom rating component, we have need material components like buttons, icon and we need to import this module inside the app.module.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { RatingComponent } from './components/rating/rating.component';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    RatingComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatIconModule,
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Let create an Angular custom rating component and edit the rating.component.html

<div class="container">
   <button mat-icon-button color="accent" 
     *ngFor="let ratingId of ratingArray;
     index as i" [id]="'star_'+i" (click)="calculateRating(i+1)">
        <mat-icon>
            {{ iconStatus(i) }}
        </mat-icon>
    </button>
    <p>
        Your rated <span>{{ rating }}</span>/<span>{{ totalStar }}</span>
    </p>
</div>

Where ratingArray is an array of numbers from 0 to 4, it means we have 5 buttons which we are iterating in *ngFor loop. The calculateRating will check if the star rating button toggle on or off based on its current status.

The iconStatus method will return full star or outline start based on start rating status. Let implement the above method inside the app.component.ts file.

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'mat-star-rating',
  templateUrl: './rating.component.html',
  styleUrls: ['./rating.component.scss']
})
export class RatingComponent implements OnInit {
  @Input('rating') rating: number = 3;
  @Output() ratingUpdated = new EventEmitter();

  totalStar: number = 5;
  ratingArray: number[] = [];

  constructor() { }

  ngOnInit() {
    for (let index = 0; index < this.totalStar; index++) {
      this.ratingArray.push(index);
    }
  }
  
  calculateRating(rating: number) {
    this.ratingUpdated.emit(rating);
  }

  iconStatus(index: number) {
    if (this.rating >= index + 1) {
      return 'star';
    } else {
      return 'star_border';
    }
  }
}

The rating is a child component, we have used an event emitter to emit the current rating value to its parent component in the calculateRating function.

In the parent component, in our case the app.component.ts file, we need to add child component rating,

<mat-star-rating [rating]="rating" (ratingUpdated)="onRatingChanged($event)"></mat-star-rating>
<router-outlet></router-outlet>

The onRatingChange method will receive a rating value from the child rating component, let define the onRatingChanged method in the app.component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  rating: number = 3;
  starCount: number = 5;

  onRatingChanged(rating: number) {
    this.rating = rating;
  }
}

Angular Material star rating example using ngx-material-rating

We’ll demonstrate star rating using third-party library the ngx-material-rating. Here we first need to install this library in our project by following the command.

ng new starRatingApp
cd starRatingApp
npm i ngx-material-rating --save

Here is a screenshot of our first example of ngx-material-rating example.

Angular star rating
Angular Material star rating

To use this library in our angular project, we need to import NgxMaterialRatingModule in our app.module.ts file and let edit the app.module.ts file.

...
import { NgxMaterialRatingModule } from 'ngx-material-rating';

@NgModule({
  declarations: [
    AppComponent,
    RatingComponent
  ],
  imports: [
    ...
    NgxMaterialRatingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have an import the NgxMaterialRatingModule module. Let’s demonstrate a few examples of ngx-material-rating in our Angular project. First, we need array variable ratings of type Rating and it can hold color values and an array containing lists of ratings.

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

interface Rating {
  value: number;
  max: number;
  color?: ThemePalette;
  disabled?: boolean;
  dense?: boolean;
  readonly?: boolean;
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  ratings: Rating[] = [
    {
      value: 1,
      max: 10,
      color: "primary"
    },
    {
      value: 2,
      max: 5,
      color: "accent"
    },
    {
      value: 3,
      max: 10,
      color: "warn"
    },
    {
      value: 4,
      max: 5
    },
    {
      value: 5,
      max: 10,
      disabled: true
    },
    {
      value: 1,
      max: 5,
      color: "primary",
      dense: true
    },
    {
      value: 2,
      max: 5,
      color: "accent",
      readonly: true
    }
  ];
}

Let edit the app.component.html template to demonstrate the Angular star rating example.

<main>
    <h1>Using <code>ngx-material-rating</code></h1>

    <ng-container *ngFor="let rating of ratings; index as i">
        <div class="rating">
            <span>
                Rating {{rating.value}} of {{rating.max}}
            </span>
            <div>
                <ngx-material-rating [color]="rating.color" [(ngModel)]="ratings[i].value" [max]="rating.max">
                </ngx-material-rating>
            </div>
        </div>
    </ng-container>
</main>

Conclusion:
We have completed our Angular rating component using a few libraries, if you are using Bootstrap UI in your Angular project then it’s best and easy to use the Bootstrap rating component. Angular material doesn’t have a rating component, we can use the ngx-material-rating, but I guess is best to create our own custom rating component.

I hope you had learned something, if so then please share it with others and on social networks, this will encourage me to add more content. Follow me on my GitHub collection, I had code on Angular, react and Ionic framework.

Related Post

Different ways of adding Angular star rating component.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top