Counter for nested ngFor loops in Angular2
Asked Answered
I

2

20

I have two nested *ngFor loops in Angular2. 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

  <tr *ngFor="let adjustment of adjustments">

    <td *ngFor="let blade of blades">

      <span> Counter =  ?????????  </span>

    </td>

  </tr>
Indiscernible answered 13/2, 2017 at 9:11 Comment(0)
I
34

Add a counter variable to both *ngFor statements, say i and j, then do the maths as an expression. 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>
Indiscernible answered 13/2, 2017 at 9:42 Comment(1)
It won't work if the size of blades in each adjstment is diffrent ...Brooks
C
0

If for each adjustment list the corresponding blades list is different. Then Use below. Consider lstMain as Adjustments and lstChild as Blades. lstMain =[ {lstChild:{1,2}},{lstChild:{5,6,7,8}},{lstChild:{12}},{lstChild:{14,15,16}} ] Take this example ,It will give correct data. 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.

<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;
}
Clamp answered 4/6, 2021 at 11:50 Comment(2)
lstMain =[ {lstChild:{1,2,3,4}},{lstChild:{5,6,7,8}},{lstChild:{9,10,11,12}},{lstChild:{13,14,15,16}} ] Take this example ,It will give correct data. 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.Clamp
The SetSeqNo method will be called each time an event occurs on your componentBrooks

© 2022 - 2024 — McMap. All rights reserved.