[英]Counter for nested ngFor loops in Angular2
I have two nested *ngFor loops in Angular2.我在 Angular2 中有两个嵌套的 *ngFor 循环。 I want to maintain a counter that increments each time the code at the center of the loops is repeated.
我想维护一个计数器,每次重复循环中心的代码时都会增加。
The counter should go from 0 to the number of adjustments times the number of blades计数器应从 0 到调整次数乘以刀片数
<tr *ngFor="let adjustment of adjustments">
<td *ngFor="let blade of blades">
<span> Counter = ????????? </span>
</td>
</tr>
Add a counter variable to both *ngFor statements, say i and j, then do the maths as an expression.将计数器变量添加到 *ngFor 语句,例如 i 和 j,然后将数学作为表达式进行计算。 Here is the code:
这是代码:
<tr *ngFor="let adjustment of adjustments; let i = index">
<td *ngFor="let blade of blades; let j = index">
<span> Counter = {{ (i * blades.length) + j }} </span>
</td>
</tr>
If for each adjustment list the corresponding blades list is different.如果每个调整列表对应的刀片列表不同。 Then Use below.
然后在下面使用。 Consider lstMain as Adjustments and lstChild as Blades.
将 lstMain 视为调整项,将 lstChild 视为刀片。 lstMain =[ {lstChild:{1,2}},{lstChild:{5,6,7,8}},{lstChild:{12}},{lstChild:{14,15,16}} ] Take this example ,It will give correct data.
lstMain =[ {lstChild:{1,2}},{lstChild:{5,6,7,8}},{lstChild:{12}},{lstChild:{14,15,16}} ] 拿这个例子,它会给出正确的数据。 Basically in SetSeqNo Method the counter variable is calculating the past lstChild length of previous iterations then adding in it the current index j which will give the exact counter value of current index.
基本上在 SetSeqNo 方法中,计数器变量计算先前迭代的过去 lstChild 长度,然后将当前索引 j 添加到其中,这将给出当前索引的确切计数器值。
<ng-container *ngFor="let obj of lstMain;let i=index">
<ng-container *ngFor="let child of obj.lstChild;let j=index">
<tr>
<td>
<span>{{SetSeqNo(i,j,lstMain)}}</span>
</td>
</tr>
</ng-container>
</ng-container>
SetSeqNo(i,j,lst){
let Counter=0;
for(let k=0;k<=i-1;k++){
Counter=Counter+lst[k].lstChild.length;
}
return Counter + j + 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.