Home > Software design >  How to iterate cards within same container in angular
How to iterate cards within same container in angular

Time:02-16

I have this JSON object:

data=[
  {
    id:1,
    name:'Alex'
  },
  {
    id:2,
    name:'John'
  },
  {
    id:3,
    name:'Sam'
  },
  {
    id:4,
    name:'Top'
  },{
    id:5,
    name:'Jose'
  }
,
{
    id:6,
    name:'Malan'
  }
,
{
    id:7,
    name:'Jo'
  }
]

I want to iterate and print each name in a row. per row 2 items.

Expected result

// first two names
<div>
  name:'Alex'
  name:'John'

</div>

// second two names
<div>
  name:'Sam'
  name:'Top'

</div>

I want to print every two names in the same container. How to achieve this using *ngFor.

CodePudding user response:

How about grouping the data and using 2 levels of ngfor loops?

const data=[{id:1, name:'Alex'},{id:2,name:'John'},{id:3,name:'Sam'},{id:4,name:'Top'},{id:5,name:'Jose'},{id:6,name:'Malan'},{id:7,name:'Jo'}]

let result = []
data.forEach((d,i) =>{
  i%2 == 0 && result.push([]);
  result[result.length-1].push(d)
  }
)
console.log(result)
this will result a grouped json;

and then add one another loop inside you first loop

CodePudding user response:

You could use the array chunk function from here and implement a pipe in Angular.

chunk-array.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'chunkArray',
  pure: true,
})
export class ChunkArrayPipe implements PipeTransform {
  // credit: https://stackoverflow.com/questions/8495687/split-array-into-chunks#comment84212474_8495740
  transform(array: any, chunkSize: number, property?: string): any {
    return Array(Math.ceil(array.length / chunkSize))
      .fill(null)
      .map((_, index) => index * chunkSize)
      .map((begin) =>
        array
          .map((item: any) => (!!property ? item[property] : item))
          .slice(begin, begin   chunkSize)
      );
  }
}

And use it in the template

<ng-container *ngFor="let item of data | chunkArray: 2:'name'">
  <div>
    <ng-container *ngFor="let name of item">
      Name: {{ name }} <br />
    </ng-container>
  </div>
  <hr />
</ng-container>

Working example: Stackblitz

  • Related