1

Is there any clean way to iterate over an array of articles in a way described below?

I have an array of articles which i want to print in rows. Each row should contain 3 articles, so the template should be something like:

<row>
 <article id=1></article>
 <article id=2></article>
 <article id=3></article>
</row>
<row>
 <article id=4></article>
 <article id=5></article>
 <article id=6></article>
</row>

Easiest solution I made up now would be:

  1. Calculate the length of array with articles, divide it by 3, get the number of rows
  2. Create an array with integers from 0 to calculated number
  3. In the template create a <row></row> with ngFor over the array of integers
  4. Inside each row create another ngFor containing articles with ngIf over the index of outer loop and some funky condition.

Is there any other way to nicely print out such case in Angular2?

1 Answer 1

2

One solution is to chunk your data into arrays for each row, then use nested *ngFor loops to iterate over them. This can be achieved with a custom pipe:

<row *ngFor="let row of articles | chunk: 3; let i = index">
  <ng-container *ngFor="let article of row; let j = index">
    <article id='(i*3)+j'></article>
  </ng-container>
</row>

The chunk pipe can either use lodash _.chunk, or natively shown below:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'chunk'
})
export class ChunkPipe implements PipeTransform {

  transform(value: any, n: number): any {
      return this.chunk(value, n);
  }

  chunk(arr, n) {
      let newArr = [];
      let nestedArr = [];
      for (let i = 1; i <= arr.length; i++) {
          nestedArr.push(arr[i - 1]);
          if (i % n === 0) {
              newArr.push(nestedArr);
              nestedArr = [];
          }
      }
      if (nestedArr.length > 0) {
          newArr.push(nestedArr);
      }
      return newArr;
  }
}

I've created a working plunkr as an example

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.