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.ts
import { 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.scss
ul 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
Top comments (2)
what is the function of (&:) ;
thanks .
It is
scsssyntax. You can refer to sass-lang.com/ for further details.