Monday, 16 October 2017

Reusable rating star component using angular

AngularRatingRating star component

In this article I will be discussing about implementing a simple rating star component. This component can be reused very easily. Let us check with a working example.


<rating-star max = 10 (onRating) = onRating($event)></rating-star>

Above is the simple representation of a rating star component, this you can add any where in your application. Now let us check the component code. Here by using onRating method you can get the selected rating count.

Rating star Component


<div>
  <span class="icon" *ngFor="let s of maxItem">
    <i [ngClass]=" s <= this.ratedCount ? 'filled' :'' "
       class="fa fa-star"
       aria-hidden="true" (click)="toggleRating(s)"></i>
  </span>
</div>


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

@Component({
  selector: 'rating-star',
  templateUrl: './rating-star.component.html',
  styleUrls: ['./rating-star.component.scss']
})
export class RatingStarComponent implements OnInit {

  @Input() max: number;
  @Output() onRating = new EventEmitter<number>();

  public maxItem: any[];
  public ratedCount: number;

  constructor() {
    this.ratedCount = 0;
  }

  ngOnInit() {
    this.maxItem = [];
    for (let i = 0; i < this.max; i++) {
      this.maxItem.push(i + 1);
    }
  }

  public toggleRating(s: number): void {
    this.ratedCount = s;
    this.onRating.emit(this.ratedCount);
  }

}

Parent component

Here you can get the selected rating count. Check below code.


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

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

export class AppComponent {
  public title : string;

  constructor(){
    this.title = 'Rating stars using Angular';
  }

  public onRating(rating : number): void {
    console.log(rating);
  }
}

Advantage of using this way is that you can reuse this component any where in your application. Using onRating output emitter you can get the selected start count. If you want to use this logic also inside the rating start component then remove this output emitter and use this method directly inside the rating star component.

I will share my css code as well, basically for coloring the star and some look and feel. Here I have used fontawesome icons, you can replace with any icon.

css


.icon{
    display:inline-block;
    margin-right:3px;
    cursor:pointer;
    color:#ccc;
}
.icon:hover{color:#006dcc;}
.filled {color:#006dcc;}

And we are done. You need to import this component in your module for to work everywhere. My suggestion is to keep in your shared module so that you can use this across your application. check below module code.

Module


import {ModuleWithProviders, NgModule} from '@angular/core';
import { CommonModule } from '@angular/common';
import {RatingStarComponent} from './components/rating-star/rating-star.component';

@NgModule({
  declarations: [RatingStarComponent],
  imports: [
    CommonModule
  ],
  exports: [RatingStarComponent]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: []
    };
  }
}

Demo

Set initial rating value


If you want to set initial rating you can update the code like below.


<rating-star setRating = 2 max = 10 (onRating) = onRating($event)></rating-star>

Here we are setting initial rating as 2. Update our rating component as well.


//add input
 @Input() setRating : number;
 
  //set in our ngOnInit methode
  ngOnInit(){
     this.ratedCount = this.setRating;
    //etc 
 }

If you want to know more about reusable component refer this link. In this article we have discussed about creating a simple rating star component using Angular.

AngularRatingRating star component

Related Info

1. How to show a date is today or yesterday or last week etc using pipe - Angular

2. Disable submit button until all mandatory fields are filled - Angular

3. Angular client side pagination.

4. Angular show more/less pagination

6 comments :

  1. Thanks a lot! was a very helpful tutorial :)

    ReplyDelete
  2. thanks alot.. i have been searching for angular rating for so go....

    but i had an err:
    Identifier 'onRating' is not defined. The component declaration, template variable declarations, and element references do not contain such a member

    ReplyDelete
    Replies
    1. onRating method is used to get the selected rating count to parent component, please add this method into your parent component. If you are handling this also in the same component then use this method in the rating component it self. Then remove this output emitter.

      Delete
  3. will it work on angular 9?

    ReplyDelete
    Replies
    1. Yes, I recently tested, it is working fine.

      Delete