Star Rating in Angular Forms

In my last article we discuss on how to use Typehead in angular application. In these tutorial i discuss on how to add star-rating in our Angular Forms.
First we need to add below line in our app.module.ts file.


.................
//we need to import first Rating Module From Bootstrap.
import { RatingModule } from 'ngx-bootstrap';
...................
@NgModule({
  .........
  imports: [
                RatingModule.forRoot(),
            ...
           ]
})
export class AppModule(){}



After adding RatingModule in the app module file. Now we can use these in any component.
Let’s create Basic code for the star-rating elements.


<rating [(ngModel)]="rate" [max]="max"></rating>


import { Component } from '@angular/core';
 
@Component({
  selector: 'starrating-basic',
  templateUrl: './starrating.html'
})
export class starRatingComponent {
  max: number = 5;
  rate: number = 2;
}


From above code you can easily set star-rating. we have mainly two attributes here
1) MAX: maximum value of the Star Rating.
2) rate: its a variable of ngModel sot its change value we can get that value easily in an function we get value of the Star Rating.

Their is Read-only parameter you can pass so value not changeable. Example display in below example.


<rating [(ngModel)]="rate" [max]="max" [readonly]="isReadonly" ></rating>


import { Component } from '@angular/core';
 
@Component({
  selector: 'starrating-basic',
  templateUrl: './starrating.html'
})
export class starRatingComponent {
  max: number = 5;
  rate: number = 2;
 isReadonly: boolean = true;
}




When Hover trigger star rating value change also add title of each display in Below Example.


<rating [(ngModel)]="rate" [max]="max" [readonly]="isReadonly"
(onHover)="hoveringOver($event)" (onLeave)="resetStar()"
[titles]="['Star 1','Star 2','Star 3','Star 4','Star 5']">
</rating>
<span class="label"
      [ngClass]="{'label-warning': percent<30, 'label-info': percent>=30 && percent<70, 'label-success': percent>=70}"
      [ngStyle]="{display: (overStar && !isReadonly) ? 'inline' : 'none'}">{{percent}}%</span>


import { Component } from '@angular/core';
 
@Component({
  selector: 'starrating-basic',
  templateUrl: './starrating.html'
})
export class starRatingComponent {
  max: number = 5;
  rate: number = 2;
  isReadonly: boolean = false;
  overStar: number;
  percent: number;

  hoveringOver(value: number): void {
    this.overStar = value;
    this.percent = (value / this.max) * 100;
  }
 
  resetStar(): void {
    this.overStar = void 0;
  }

}

Output of above all code display in below video

Spread the love
  • 24
  •  
  •  
  •  
  •  
  •  
  •  
  •