Using Angular2 ngFor index Using Angular2 ngFor index angular angular

Using Angular2 ngFor index


Angular does not provide this functionality out of the box. I think that the simplest way to achieve the desired result is to only display data on every third index like so:

<div class="list-group">  <div *ngFor="let p of products; let idx = index" >    <div class="row" *ngIf="idx % 3 === 0">      <app-product [product]="products[idx]"></app-product>      <app-product [product]="products[idx+1]"></app-product>      <app-product [product]="products[idx+2]"></app-product>    </div>  </div></div>

Demo


For index try this:

Controller File add function :

chunks(array, size) {  let results = [];  while (array.length) {    results.push(array.splice(0, size));  }  return results;};

In you view file :

<div *ngFor="let chunkProduct of chunks(products,3);" >  <div class="row">      <app-product *ngFor="let product of chunkProduct" [product]="product"></app-product>  </div></div>

This will work for all number , not only %3 numbers.

@Teddy Sterne's solution will work incase of the number is %3 If we have 8 products it will show only 6 last 2 will be lost , in this it will also be shown.

And it will create extra blank div tags for not %3 index , if you inspect the element and check , because it will loop through each product and div will get repeated no matter if its index %3 or not.


Thanks Teddy Sterne for his answer.

Here's how it helped me to create a calendar control having 7 cells in a row

<div class="container-fluid">  <table class="table table-bordered">    <ng-container *ngFor="let d of data; let i = index" >      <tr *ngIf="i % 7 === 0">        <td *ngFor="let x of [i,i+1,i+2,i+3,i+4,i+5,i+6]">          {{data[x]}}        </td>      </tr>    </ng-container>  </table>      </div> 

DEMO

https://stackblitz.com/edit/angular-1nhor2?embed=1&file=src/app/app.component.html