user14092249
user14092249

Reputation:

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

Upvotes: 0

Views: 569

Answers (2)

Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5021

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 ;)

Upvotes: 0

Zer0
Zer0

Reputation: 1690

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>

Upvotes: 1

Related Questions