本文介绍了使用Angular2 ngFor索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码:
<div class="row list-group">
<div *ngFor="let product of products" >
<app-product [product]="product"></app-product>
</div>
</div>
我想知道有什么办法可以从存储桶中的阵列中获取产品吗?像这样:
I was wondering is there any way i can get products from array in buckets? Something like this:
<div class="list-group">
<div *ngFor="products; index+3" >
<div class="row">
<app-product [product]="products[index]"></app-product>
<app-product [product]="products[index+1]"></app-product>
<app-product [product]="products[index+2]"></app-product>
</div>
</div>
</div>
这样,我可以连续获得所有需要的元素
That way I could have all elements i need in a row
UPD
感谢泰迪·斯特恩(Teddy Sterne),我最终提出了以下解决方案:
Thanks to Teddy Sterne I ended up with this solution:
<div class="list-group">
<div *ngFor="let product of products;let i = index">
<div class="row" *ngIf="i%3===0">
<app-product [product]="products[i]"></app-product>
<div *ngIf="products[i + 1]">
<app-product [product]="products[i + 1]"></app-product>
</div>
<div *ngIf="products[i + 2]">
<app-product [product]="products[i + 2]"></app-product>
</div>
</div>
</div>
</div>
推荐答案
Angular不提供开箱即用的功能.我认为,达到预期结果的最简单方法是仅在每三个索引上显示数据,如下所示:
Angular does not provide this functionality out of the box. I think that the simplest way to achieve the desired result is to only display data on every third index like so:
<div class="list-group">
<div *ngFor="let p of products; let idx = index" >
<div class="row" *ngIf="idx % 3 === 0">
<app-product [product]="products[idx]"></app-product>
<app-product [product]="products[idx+1]"></app-product>
<app-product [product]="products[idx+2]"></app-product>
</div>
</div>
</div>
这篇关于使用Angular2 ngFor索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!