问题
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