问题描述
以下是我现在所拥有的:
<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}} 条评论)</span></a>您可能已经猜到了,它会根据产品的星数重复一个星形图标.它按原样运行,但是,我觉得必须有更好的方法.理想情况下,我想使用:
<i *ngFor="+product.rating.avgStars" class="fa fa-star"></i>
我知道我可以潜在地使用指令或管道来封装此功能;我只是问有没有办法使用内置的角度指令来任意重复 HTML 标签.
解决方案 在您使用适当数量的星星填充的组件中创建一个支持数组
class RatingComponent {ngOnInit() {myRating = Array(numberOfStarsFromSomewhere).fill('whatever');}}<i *ngFor="let rating of myRating" class="fa fa-star"></i>
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.
解决方案 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>
这篇关于我可以使用内置的角度指令重复 *ngFor 任意次数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-02 01:29