Can I repeat *ngFor an arbitrary number of times using built in angular directives?

妖精的绣舞 提交于 2019-12-24 11:03:04

问题


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.


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/40251160/can-i-repeat-ngfor-an-arbitrary-number-of-times-using-built-in-angular-directiv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!