1

Below is what I have now:

<div class="reviews">
    <a href="#">
        <i *ngIf="product.rating.avgStars >= 1" class="fa fa-star"></i>
        <i *ngIf="product.rating.avgStars >= 2" class="fa fa-star"></i>
        <i *ngIf="product.rating.avgStars >= 3" class="fa fa-star"></i>
        <i *ngIf="product.rating.avgStars >= 4" class="fa fa-star"></i>
        <i *ngIf="product.rating.avgStars >= 5" class="fa fa-star"></i>
    <span class="amount">({{product.rating.reviewCount}} Reviews)</span>
</a>

As you may have guessed, it will repeat a star icon for the number of stars a product has. It works as is, however, I feel like there must be a better way. Ideally I would like to use:

<i *ngFor="+product.rating.avgStars" class="fa fa-star"></i>

I am aware that I can potentially use directives or pipes to encapsulate this functionality; I am simply asking is there is a way to use built in angular directives to arbitrarily repeat an HTML tag.

jake
  • 488
  • 10
  • 19
  • 2
    Possible duplicate of [Repeat HTML element multiple times using ngFor based on a number](http://stackoverflow.com/questions/36535629/repeat-html-element-multiple-times-using-ngfor-based-on-a-number) – Harry Ninh Oct 25 '16 at 23:17
  • I bolded my clarification for you, I was specifically asking about built in angular directives. I am not asking how, I am asking if there is a way to do it better. – jake Oct 25 '16 at 23:47
  • The referenced question/answer also mentions using an array. You could add a member `array: Function = Array` and use that in the template ``. Which looks like a reasonable way of doing it. – cartant Oct 26 '16 at 00:18

2 Answers2

2

Create a backing array in the component that you populate with the appropriate number of stars

class RatingComponent {
  ngOnInit() {
    myRating = Array(numberOfStarsFromSomewhere).fill('whatever');
  }
}

<i *ngFor="let rating of myRating" class="fa fa-star"></i>
TGH
  • 38,769
  • 12
  • 102
  • 135
1

In your component file create a variable of type array

export class RenewPackageComponent implements OnInit {
 myArr = Array;
}

In your Html file

<i *ngFor="let i of myArr(product.rating.avgStars)" class="fa fa-star"></i>
Pooja
  • 356
  • 2
  • 11