3

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

1

From the pattern it looks like a outer and a inner loop will solve the problem. outer loop will control the "row" - div inner loop will control the "col-6" - div Kindly give it a try.

1 Comment

So do I have to calculate how many row I would need if I had x elements? For example 12 elements means 6 rows. Does it have to be so complicated?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.