Home > Mobile >  Loop Vertically One column at a time
Loop Vertically One column at a time

Time:03-08

I wanted to loop through an array of objects and show 4 of them vertically in one column before displaying the items in the second column.

Right now I can print the items like this

enter image description here

I need it like this

enter image description here

I can always break down the array into 2 sub-arrays and display it individually in each column. Was wondering if there was a better way to implement it.

https://stackblitz.com/edit/angular-ivy-acelg2

CodePudding user response:

If you don't know the heigth of your elements, you can always split your data in an array of two elements

serviceColumn=[this.serviceList.filter((_,i)=>i<4),
               this.serviceList.filter((_,i)=>i>=4)]


<div style="display:flex">
  <div *ngFor="let i of [0, 1]">
    <div *ngFor="let service of serviceColumn[i]">
      <span>{{ service.name }}</span>
      <span>{{ service.count }}</span>
    </div>
  </div>
</div>

Or use slice pipe

<div style="display:flex">
  <div *ngFor="let i of [0, 1]">
    <div *ngFor="let service of serviceList | slice: i * 4:(i   1) * 4">
      <span>{{ service.name }}</span>
      <span>{{ service.count }}</span>
    </div>
  </div>
</div>

If you has an observable, not an array you can use some like

<div style="display:flex" *ngIf="serviceList$ | async as list">
  <div *ngFor="let i of [0, 1]">
    <div *ngFor="let service of list | slice: i * 4:(i   1) * 4">
      <span>{{ service.name }}</span>
      <span>{{ service.count }}</span>
    </div>
  </div>
</div>

see the stackblitz

CodePudding user response:

The CSS way:

Instead of using flexbox on your container, why not use column-count ?

The column-count CSS property breaks an element's content into the specified number of columns.

MDN : column-count

Demo:

ul {
  list-style: none;
  column-count: 2;
}
<ul><li>item 1 - 10</li>
  <li>item 2 - 20</li>
  <li>item 3 - 30</li>
  <li>item 4 - 40</li>
  <li>item 5 - 50</li>
  <li>item 6 - 60</li>
  <li>item 7 - 70</li>
  <li>item 8 - 80</li>
</ul>

  • Related