NickD
NickD

Reputation: 69

Angular ngFor split by divs

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.

Upvotes: 1

Views: 1595

Answers (1)

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

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

Upvotes: 3

Related Questions