Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you loop through different rows (bootstrap rows) in Angular?

I am asking myself: How would you loop through different rows using *ngFor? Lets say an array is given

let arr = [1,2,3,4] // arr can have a arbitrary number of elements

Now I want to loop trough that array and display the values. I want two elements to be in a row (using bootstrap 4.0). My approach:

<div class="row">
    <div class="col-6" *ngFor="let el of arr"> {{el}} </div>
</div>

Now I would have this html-code

<div class="row">
    <div class="col-6"> 1 </div>
    <div class="col-6"> 2 </div>
    <div class="col-6"> 3 </div>
    <div class="col-6"> 4 </div>
</div>

but I want it this way:

<div class="row">
    <div class="col-6"> 1 </div>
    <div class="col-6"> 2 </div>
</div>
<div class="row">
    <div class="col-6"> 3 </div>
    <div class="col-6"> 4 </div>
</div>

because this would be correct regarding the elements in a row. How can I achieve this?

like image 856
Logik Avatar asked Sep 10 '26 06:09

Logik


2 Answers

You can achieve it without second loop provided col-6 is fixed.

<div>
  <ng-container  *ngFor="let el of arr; index as i">
    <div class="row" *ngIf="i%2 === 0">
            <div class="col-6" > {{arr[i]}} </div>
            <div class="col-6" > {{arr[i+1]}} </div>
    </div>
  </ng-container>
</div>

This will do as you are expecting.

like image 82
Himanshu Sharma Avatar answered Sep 11 '26 18:09

Himanshu Sharma


Option 1

The quickest option would be to use the slice pipe. But it might not be suitable for large data sets.

<div class="row">
  <div class="col-6" *ngFor="let el of arr | slice:0:2"> {{el}} </div>
</div>
<div class="row">
  <div class="col-6" *ngFor="let el of arr | slice:2:4"> {{el}} </div>
</div>

Option 2

Split the array into chunks of arrays and loop through them.

Controller

export class AppComponent  {
  arr = [1,2,3,4];
  finalArr = [];    // <-- [[1,2], [3,4]]

  constructor(private http: HttpClient){
    for (let i = 0, j = this.arr.length; i < j; i += 2) {
      this.finalArr.push(this.arr.slice(i, i + 2));
    }
  }
}

Template

<div class="row" *ngFor="let arr of finalArr">
  <div class="col-6" *ngFor="let el of arr"> {{el}} </div>
</div>
like image 37
ruth Avatar answered Sep 11 '26 19:09

ruth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!