0

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

2 Answers2

1

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>
Zer0
  • 1,580
  • 10
  • 28
  • Weird, it worked for me in the stackblitz, let me check again – Zer0 Aug 31 '20 at 15:11
  • Yeah it works man seems like there was something not going well on my connection.Thank you so much –  Aug 31 '20 at 16:41
0

You can try like below. Use *ngFor exported value index and use half length of the array to continue the loop

<ng-container *ngFor="let item of studentNames; let j = index;">
  <ng-container *ngIf="j < (studentNames.length / 2)">
    <div class="row">
      <div class="col md-6">
        {{item.name}}
      </div>
      <div class="col md-6">
        {{ studentNames[ j + (studentNames.length / 2) ].name }}
      </div>
    </div>
  </ng-container>
</ng-container>

Working stackblitz

Note : Array length should be an even number ;)

Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56