Counter for nested ngFor loops in Angular2

CodeCabbie picture CodeCabbie · Feb 13, 2017 · Viewed 21.4k times · Source

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>

Answer

CodeCabbie picture CodeCabbie · Feb 13, 2017

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>