Search code examples
cssangularflexboxngfor

Show fix 4 flex box in one row


The main target is I would like to show fix 4 boxes in one row.I would like to show like that=>

 <div class="flex-container">
    <div class="flex-row">
        <box></box>
        <box></box>
        <box></box>
        <box></box>
    </div>
    <div class="flex-row">
        <box></box>
        <box></box>
        <box></box>
        <box></box>
    </div>
</div>

I have boxes array like that=>

<box *ngFor="let info of infolist;let i = index"></box>

but this one shows like that=>

   <div class="flex-container">
     <box></box>
     <box></box>
     <box></box>
     <box></box>
     <box></box>
     <box></box>
     <box></box>
     <box></box>
     <box></box>
   </div>

here is my css=>

.flex-container{
    display: flex;
    flex-wrap: wrap; 
    justify-content: center; 
}

.flex-container .flex-row{
    display: flex;
    flex-wrap: nowrap;
}

How can I show fix 4 flexbox in one row?


Solution

  • You could leverage chunks pipe like:

    @Pipe({
      name: 'chunks'
    })
    export class ChunksPipe implements PipeTransform {
      transform(arr: any, chunkSize: number) {
        return arr.reduce((prev, cur, i) => (i % chunkSize) ? prev : prev.concat([arr.slice(i, i + chunkSize)]), []);
      }
    }
    

    with the following template:

    <div class="flex-container">
        <div class="flex-row" *ngFor="let chunk of infoList | chunks: 4">
           <box *ngFor="let box of chunk">{{box}}</box>
        </div>
    </div>
    

    Stackblitz Example

    Or you can rethink your HTML structure and just use flat structure with width: 25% for each box.