Search code examples
angularflexboxtailwind-cssngfor

Split *ngFor data into 2 columns


I have this HTML:

<div class="w-full flex justify-center">
  <div *ngFor="let item of items" class="flex w-1/2">
    <span>{{item.label}}</span>
    <span>{{item.value}}</span>
  </div>
</div>

This way, the HTML in UI is displayed as:

LABEL 1 - VALUE 1 | LABEL 2 - VALUE 2
LABEL 3 - VALUE 3 | LABEL 4 - VALUE 4
LABEL 5 - VALUE 5 | LABEL 6 - VALUE 6

I need to display data like this:

LABEL 1 - VALUE 1 | LABEL 4 - VALUE 4
LABEL 2 - VALUE 2 | LABEL 5 - VALUE 5
LABEL 3 - VALUE 3 | LABEL 6 - VALUE 6

I´ve been trying to find a working solution but without luck. Can you suggest a working solution?


Solution

  • Chunk the items array into half.

    chunkedItems: any[][] = [];
    
    let halfIndex = Math.floor(this.items.length / 2);
    this.chunkedItems = [
      this.items.slice(0, halfIndex),
      this.items.slice(halfIndex, this.items.length),
      ];
    }
    

    And structure the flex containers as below:

    <div class="w-full flex flex-wrap justify-center">
      <ng-container *ngFor="let chunks of chunkedItems; let i = index">
        <div class="flex flex-col w-1/2">
          <div *ngFor="let item of chunks" class="flex">
            <span>{{item.label}}</span> -
            <span>{{item.value}}</span>
          </div>
        </div>
      </ng-container>
    </div>
    

    Demo @ StackBlitz