Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 14, 2022 04:11 am GMT

Angular: Star rating with no external libraries

It is a very simple and very much needed small component required in every other blog to rate the services provided.

Mostly, developers want to use some external start-rating libraries to show much styled and very interactive stars. Though, We can also create such stylistic stars using native JS and CSS support.

I always prefer to write things natively hence here is my implementation for the star rating without using any libraries.

Please let me know any improvements. I am always happy to update the article.

// app.component.tsimport { Component } from '@angular/core';@Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: ['./app.component.scss'],})export class AppComponent {  title = 'Star Rating';  arr: any[] = [];  index: number = 0;  constructor() {    this.arr = [      { value: 1, color: 'black' },      { value: 2, color: 'black' },      { value: 3, color: 'black' },      { value: 4, color: 'black' },      { value: 5, color: 'black' }    ];  }  onClickItem(index: number) {    this.index = index;    this.manipulateArr(index);  }  onMouseHover(index: number) {    this.manipulateArr(index);  }  onMouseLeave() {    this.manipulateArr(this.index);  }  manipulateArr(index) {    this.arr.forEach((item, i) => {      if (i <= index - 1) {        item.color = 'green';      } else {        item.color = 'black';      }    });  }}
<!--app.component.html--><div>  <ul>    <li *ngFor="let item of arr" (click)="onClickItem(item.value)" (mouseover)="onMouseHover(item.value)"      (mouseleave)="onMouseLeave()" [style.color]="item.color">*    </li>  </ul></div><p>User Rated: {{ index }}/5</p>
// app.component.scssul li {  width: 60px;  cursor: pointer;  display: inline-block;  font-size: 80px;  &:hover {    color: green;  }}

Mostly, everything written is self explanatory. But, explanation always help to the newbies.

In HTML, I populated stars using arr of items with symbol * (available on keyboard) using ul. This arr initialized with 5 elements hence 5-stars displayed. You can see the ts file for the initialized array.

If user hovers on it then its color will change to green otherwise black and it has been handled using two events mouseover and mouseleave and the corresponding methods have been executed each time.

Also, when user clicks on any star then count has been updated below as User Rated: 4/5 and color will be green till selected.

You can follow me: https://twitter.com/urstrulyvishwak

Here you can see how it works:

Thanks


Original Link: https://dev.to/urstrulyvishwak/star-rating-with-no-external-libraries-in-angular-1lp5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To