Search code examples
javascriptangularionic2ratengfor

Ionic2 + Angular2 - dynamic rate value with ion-icon star


I'm trying to build a simple dynamic rate from 0 to 5 stars (and its middle values like x.5 [example 4.5] ) that receives a value from the javascript.

I looked for something with *ngFor but I'm not understanding how that works. Can someone explain / help me?

If it helps, for ionic, we have 3 type of stars available:

<ion-icon name="star"></ion-icon>
<ion-icon name="star-half"></ion-icon>
<ion-icon name="star-outline"></ion-icon>

For example if I receive from server a value rate = 3.5, it renders:

<ion-icon name="star"></ion-icon>
<ion-icon name="star"></ion-icon>
<ion-icon name="star"></ion-icon>
<ion-icon name="star-half"></ion-icon>
<ion-icon name="star-outline"></ion-icon>

I'm using javascript, no typescript.

Thank you so much :)

p.s. not sure if this title is the better, any suggestion is welcome :)


Solution

  • Here's one way to do it:

    <ion-item>
      <ion-icon *ngIf="myRating>=1" name="star"></ion-icon>
      <ion-icon *ngIf="myRating>=2" name="star"></ion-icon>
      <ion-icon *ngIf="myRating>=3" name="star"></ion-icon>
      <ion-icon *ngIf="myRating>=4" name="star"></ion-icon>
      <ion-icon *ngIf="myRating>=5" name="star"></ion-icon>
      <ion-icon *ngIf="myRating%1!=0" name="star-half"></ion-icon>
      <ion-icon *ngIf="myRating==0" name="star-outline"></ion-icon>
      <ion-icon *ngIf="myRating<=1" name="star-outline"></ion-icon>
      <ion-icon *ngIf="myRating<=2" name="star-outline"></ion-icon>
      <ion-icon *ngIf="myRating<=3" name="star-outline"></ion-icon>
      <ion-icon *ngIf="myRating<=4" name="star-outline"></ion-icon>
    </ion-item>
    

    It takes up more space in the HTML, but doesn't require any additional javascript. Here, myRating is the star value. I tested it for all 11 possible values.