Skip to content

Instantly share code, notes, and snippets.

@rickysullivan
Created August 5, 2016 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickysullivan/99f64ca786ea54318671e83100e138b0 to your computer and use it in GitHub Desktop.
Save rickysullivan/99f64ca786ea54318671e83100e138b0 to your computer and use it in GitHub Desktop.
import { Component, OnChanges, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'ng-star-rating',
templateUrl: 'app/shared/star.component.html',
styleUrls: ['app/shared/star.component.css']
})
export class StarComponent implements OnChanges {
@Input() rating: number;
starRatings: string[] = new Array();
@Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>();
ngOnChanges(): void {
this.starValue(this.rating);
}
onClick(): void {
this.ratingClicked.emit(`${this.rating}`);
}
starValue(rating: number): void {
//For when I can convert ES6 to ES5 properly
// this.starRatings = Array.from({
// length: 5
// }, (_, i) => {
// var dif = (Math.round(rating * 2) / 2) - i;
// return dif >= 1 ? '1' : dif > 0 ? '0.5' : '0';
// })
let res: Array<string> = [];
let adjustedRating: number = (Math.round(rating * 2) / 2);
for (let i = 0; i < 5; i++) {
let dif: number = adjustedRating - i;
res.push(dif >= 1 ? '1' : dif > 0 ? '0.5' : '0');
}
this.starRatings = res;
}
starClass(index: number): string {
let rating: number = parseFloat(this.starRatings[index]);
return rating == 1 ? 'fa-star' : rating > 0 ? 'fa-star-half-o' : 'fa-star-o';
}
}
@rickysullivan
Copy link
Author

<div *ngIf="rating != undefined" class="star" [title]="rating" (click)="onClick()">
    <i class="fa" [ngClass]="starClass(i)" [attr.data-value]="starRatings[i]" aria-hidden="true" *ngFor="let i of starRatings; let i = index"></i>
</div>
<span class="alert" *ngIf="rating == undefined">
    <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> <small>No rating found</small>
</span>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment