Repeat an item for a number of times


#1

Hi
so I have this app where people can rate things , however in the API I get the rating as a number , for example I get something like this :

{[
{"name" : "john", "rating" : 3.5},
{"name" : "sarah", "rating" : 4.0}
]}

I need when I show their names to show stars as rating (I need to repeat the stars in the ratings) :

john :star: :star: :star: 3.5
sarah :star: :star: :star: :star: 4.0

after some search I found *ngFor , and *ngRepeat but the problem is that both of them are used to handle array elements whereas I need to repeat the item for a number of times


#2

You can push the item to an array the times you need to, and then use the *ngFor directive.

Don’t know if there is an alternative way in angular 2.


#3

I had this idea but it doesn’t seem right , I mean it could be a solution but I’m going to make a lot of arrays which may cause a slow performance problem , or using too much ram


#4

What do you want to do exactly?


#5

I have an app which calls an api
the api returns an array of users , each user has his name , profile pic, and rating
I need to show beside each user his rating (with stars)
here is the mockup that I’m using for now :

<button ion-button icon-left clear (click)="goToRatingPage(card.id);"><p  style="text-align:center;color:#f1ae0f;font-size:25px;width:100%;padding:0px 0">
<ion-icon name="star"></ion-icon><ion-icon name="star"></ion-icon> <ion-icon name="star"></ion-icon> <ion-icon name="star"></ion-icon> <ion-icon name="star"></ion-icon>
      </p></button>

as you can see I show five stars now for every one !


#7

Sorry I made a mistake with the last post.

Try this for every ion-icon. Probably this is not the best solution, but can work for you.

<ion-icon name="star" *ngIf="item.stars > 0"></ion-icon>
<ion-icon name="star" *ngIf="item.stars > 1"></ion-icon>
<ion-icon name="star" *ngIf="item.stars > 2"></ion-icon>
<ion-icon name="star" *ngIf="item.stars > 3"></ion-icon>
<ion-icon name="star" *ngIf="item.stars > 4"></ion-icon>

#8

I had a similar need and created a component around it like this:

import {Component, Input} from '@angular/core';

@Component({
    selector: 'rating',
    template: 
	`<ion-icon *ngFor="let n of ratingRange; let i = index" [name]="i < rating ? 'star' : 'star-outline'"></ion-icon>`
})
export class Rating {
    public ratingRange = [1, 2, 3, 4, 5];

    @Input() rating = 3;
}

You use it like this:

<rating [rating]="review.rating"></rating>

It always shows 5 stars but only fills out the ones that fit, so it may need some tweaking for your purposes.