Search code examples
javascripthtmlangulartypescriptngfor

How to create new bootstrap row per two items on Angular?


I'd like to add row on each 2 elements of ngFor loop.But I couldnt handle it. I have studentNames array like below

studentNames=[
    {
    name:"Jonas",
    age:22,
    number:"1234"
  },
      {
    name:"Mathilda",
    age:25,
    number:"5432"
  },
      {
    name:"Jacob",
    age:20,
    number:"4321"
  },
      {
    name:"Ivan",
    age:23,
    number:"6984"
  },
      {
    name:"Kate",
    age:21,
    number:"3432"
  },
      {
    name:"James",
    age:20,
    number:"4312"
  },
      {
    name:"Sean",
    age:23,
    number:"4321"
  },
      {
    name:"Julia",
    age:23,
    number:"4321"
  },
  ]

Here what I tried

<ng-container *ngFor="let item of studentNames;let i=index">
  <div class="row" *ngIf="i%2==0">
    <div class="col md-12">
      {{item.name}}
    </div>
  </div>
</ng-container>

This only skipped when index is not even. Here how I want to see them below(order doesnt matter only should be 2 by 2 per row).

enter image description here

Stackblitz example: https://stackblitz.com/edit/bootstrap-wpfukz?file=app%2Fapp.component.html


Solution

  • This is a bit more "hacky" approach but it's HTML-only:

    <ng-container *ngFor="let item of studentNames;let i=index">
        <div *ngIf="i%2==0">
            <div class="row">
                <div class="col md-12">
                    {{studentNames[i].name}}
                </div>
                <div class="col md-12">
                    {{studentNames[i + 1].name}}
                </div>
            </div>
        </div>
    </ng-container>