因此,我已经尝试了一段时间,使用*ngFor迭代一个对象数组,其中两个元素放置在一行中。在将每个组件集添加到一行之后,应该生成一个新行,以此类推。
到目前为止,我所做的尝试如下:
<div class="row" *ngFor="let prod of products; let i = index; let even = even">
<span *ngIf="even">
<div class="col-md-6 offset-3">
<div>
<img src="{{ prod.imagePath }}" alt="{{ prod.name }}" class="img-responsive" style="max-height: 150px; max-width: 150px;">
</div>
<div>
<h2>{{ prod.name }}</h2>
</div>
<div>
<h3>Price: {{ prod.price }}</h3>
</div>
</div>
<div class="col-md-6 offset-3">
<div>
<img src="{{ products[i+1].imagePath }}" alt="{{ products[i+1].name }}" class="img-responsive" style="max-height: 150px; max-width: 150px;">
</div>
<div>
<h2>{{ products[i+1].name }}</h2>
</div>
<div>
<h3>Price: {{ products[i+1].price }}</h3>
</div>
</div>
</span>
我已经核对了我在这里能找到的所有相关问题,但似乎没有一个能解决我的问题。
在这一分钟,每个元素都会进入它自己的行,而不管我做什么。
我试图更改每个元素的容器大小,但都没有效果。
提前感谢您的帮助!
发布于 2018-11-26 01:30:05
最好的方法是将产品数组的结构转换为数组数组。然后,您想要的结构是很容易循环和打印。
您可以使用pipe进行转换。例如:
@Pipe({
name: 'updateRows'
})
export class UpdateRowsPipe implements PipeTransform {
transform<T>(value: T[], perRow: number): T[][] {
let rows: T[][] = [];
for (let i = 0; i < value.length; i += perRow) {
rows.push(value.slice(i, i + perRow))
}
return rows;
}
}然后在有*ngFor的地方使用它:
<div class="row" *ngFor="let row of products | updateRows:2">
<div *ngFor="let product of row">
<div class="col-md-6 offset-3">
<div>
<img src="{{ product.imagePath }}" alt="{{ product.name }}" class="img-responsive" style="max-height: 150px; max-width: 150px;">
</div>
<div>
<h2>{{ product.name }}</h2>
</div>
<div>
<h3>Price: {{ product.price }}</h3>
</div>
</div>
<!-- Do some more fun things here -->
</div>
</div>https://stackoverflow.com/questions/53473463
复制相似问题