使用* ngFor索引将多个迭代分组为一行 [英] Use *ngFor index to group multiple iterations in one row
问题描述
我一直在尝试构建具有多列的动态输入对话框.基本上有一个字段列表,我想为每两个字段构造一个行.我的尝试看起来像这样(甚至不确定是否可行)
I've been trying to construct a dynamic input-dialog with multiple columns. Basicaly there's a list of fields and for every two fields I want to construct a row. My attempt looked like this (not even sure if this is possible)
<div *ngFor="let f of fields; let i = index">
<div class="row" *ngIf="i % 2 = 1">
<div *ngFor="let field of [fields[i],fields[i+1]]">
<div class="col-3"><label>{{field.key}}</label></div>
<div class="col-3"><input [(ngModel)]="object[field.key]"></div>
</div>
</div>
</div>
fields是对象中所有字段的映射,如下所示:
fields is a map of all the fields in object and looks like this:
[{key: fieldName,value: fieldValue},...]
显然,由于我的代码无法正常工作,因此我愿意接受其他实现的建议.
clearly since I'm here my code isn't working, I'm open to suggestions for other implementations.
推荐答案
简单的方法是将行数组预先计算为其他属性:
Simple way to do it is to precalculate rows array into additional property:
this.itemsPerRow = 2
this.rows = Array.from(
Array(Math.ceil(this.fields.length / this.itemsPerRow)).keys()
)
然后在HTML中,您将对切片管道使用两个循环:
Then in HTML you would use two loops with slice pipe:
<div *ngFor="let i of rows" class="row">
<div *ngFor="let field of fields | slice:(i*itemsPerRow):(i+1)*itemsPerRow">
<div class="col-3"><label>{{field.key}}</label></div>
<div class="col-3"><input [(ngModel)]="object[field.key]"></div>
</div>
</div>
演示: http://plnkr.co/edit/GVVyta1mqWAKP09V7Qvw ?p =预览
这篇关于使用* ngFor索引将多个迭代分组为一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!