1
votes

I have an array like this

[a, b, c, d, e, f, g, h, i]

My goal is to loop through it with ngFor split it by 3 elements, output should be like this

  <div class="wrapper">
     <div class="main">abc</div>
     <div class="main">def</div>
     <div class="main">ghi</div>
  </div>

So solution I could make is

<div class="wrapper">
      <div *ngFor="let index = index; let letter of ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']">
        <div class="main" *ngIf="(index + 1) % 3 == 0">
            {{ letter }}
        </div>
    </div>
</div>

As you can see I made div over on div with class main. But I don't need any divs over main class div. I need exactly how it shows in example.

1
Create a temporary array or a pipe which groups three letters together. - Ashish Ranjan
Why dont u make the new array in ts file and just iterate through in html? - Ntwobike
yep that or lodash chunk method + ng-container to remove the div - Jscti
if you want to use some angular directives without actualy rendering anything you can use <ng-container *ngFor="..."></ng-container> - Xesenix
Your logic is incorrect, ng-container will remove the div but will not get letters in groups of 3. - Ashish Ranjan

1 Answers

3
votes

Instead of putting logic in the HTML Code, I would construct a new array using the main array with the help of splice and join functions of Array.

So the overall code will be:

HTML:

<div class="wrapper">
    <ng-container *ngFor="let index = index; let letter of newArray">
        <div class="main">
            {{ letter }}
        </div>
    </ng-container>
</div>

TS Code:

import { Component } from '@angular/core';

@Component({
  selector: 'form-field-overview-example',
  templateUrl: 'form-field-overview-example.html',
  styleUrls: ['form-field-overview-example.css'],
})
export class FormFieldOverviewExample {

  mainArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

  newArray : any[] = [];

  constructor() {
    this.divideAndJoinArray(3);
  }

  divideAndJoinArray(spliceAt : number){
    while (this.mainArray.length) {
      var str = (this.mainArray.splice(0, spliceAt).join(''));
      console.log(str)
      this.newArray.push(str);
    }
  }
}

Stackblitz Demo