Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display review stars in angular5 view using font-awesome

I have the review stars value in the database. Example 2.5 for an item. I want to display this in the template using font-awesome.

<ul class="rating inline-ul">
    <li><i class="fa fa-star amber-text"></i></li>
    <li><i class="fa fa-star amber-text"></i></li>
    <li><i class="fa fa-star amber-text"></i></li>
   <li><i class="fa fa-star"></i></li>
   <li><i class="fa fa-star"></i></li>
</ul>

What will be the way to display the stars in accordance with the review value?

I used *ngIf, but that seems like overkill with a lot code and possibly how to represent the half stars.

 <ul class="rating inline-ul" *ngIf="2.5">
        <li><i class="fa fa-star amber-text"></i></li>
        <li><i class="fa fa-star amber-text"></i></li>
        <li><i class="fa fa-star amber-half"></i></li>
        <li><i class="fa fa-star"></i></li>
        <li><i class="fa fa-star"></i></li>
  </ul>
like image 581
LearnToday Avatar asked Nov 25 '25 12:11

LearnToday


2 Answers

Following are the code snippets:

StackBlitz url: https://stackblitz.com/edit/angular-kbmtmv

app.component.ts

export class AppComponent implements OnInit {
  value = 2.5; //addition of .5
  starList: string[] = [];
  ngOnInit() {
    let i=1;
    for(i=1; i<=5; i++) {
      if(i<= this.value) {
        this.starList.push("fas fa-star");
      } else if(i <= this.value+0.5) {
        this.starList.push("fas fa-star-half");
      } else {
        this.starList.push("far fa-star");
      }
    }
  }
}

app.component.html

<span *ngFor="let star of starList">
  <i class="{{star}}"></i>
</span>
like image 117
abbas-ak Avatar answered Nov 28 '25 03:11

abbas-ak


You can do the following. Add a new Arr property to your class

export class YourComponent {
  Arr = Array;
} 

Then, in your html:

<ul class="rating inline-ul">
        <li  *ngFor="let i of Arr(Math.floor(starValue)).fill(1)"><i class="fa fa-star amber-text"></i></li>
        <li *ngIf="starValue % 1 === 0"><i class="fa fa-star amber-half"></i></li>
 </ul>
like image 23
bugs Avatar answered Nov 28 '25 02:11

bugs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!