2

Suppose I have a list of elements like the following

items = ['AAA','BBB','CCC','DDD','EEE','FFF'];

What I am trying to do is to wrap every 2 elements in an inner-wrap div tag.

Expected output:

<div class="outer-wrap">
  <div class="inner-wrap">
    <p>AAA</p>
    <p>BBB</p>
  </div>
  <div class="inner-wrap">
    <p>CCC</p>
    <p>DDD</p>
  </div>
  <div class="inner-wrap">
    <p>EEE</p>
    <p>FFF</p>
  </div>
</dvi>

Is this feasible in the ngFor loop?

2
  • 2
    You can get the index of the current item, it shows you how to do that in the docs. You could therefore do <wrapper><thing></thing> for even indices and <thing></thing></wrapper> for odd indices. But what if there is an odd length? Alternatively, pair up the items into another array and iterate over that. It would be helpful to actually try something, then you can be specific about the problem you're having (if you still are). Commented Jan 11, 2018 at 11:19
  • Here is how you can get the index stackoverflow.com/a/29336403/340760 Commented Jan 11, 2018 at 11:22

2 Answers 2

1

You can use % (modulo) in your template to split the array in *ngFor.

Here is an working example.

So you can do this in template:

<div class="outer-wrap">
  <ng-container *ngFor="let item of testArray; let i = index;">
    <div class="inner-wrap" *ngIf="(i+1) % 2 !== 1">
      <p>{{ testArray[i-1] }}</p>
      <p>{{ item }}</p>
    </div>
  </ng-container>
</div>

Here is my testArray:

testArray: string[] = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF'];
Sign up to request clarification or add additional context in comments.

Comments

0

we can go with the custom pipe, something like the one below:

@Pipe({
  name: 'testpipe',
  pure: true,
})
export class TestPipe implements PipeTransform {
  transform<T>(value: T[], size: number): T[][] {
    let chunks: T[][] = [];
    for (let i = 0; i < value.length; i += size) {
      chunks.push(value.slice(i, i + size));
    }
    return chunks;
  }
}

now in template we can do something like below:

<div class="outer-wrap">
  <ng-container *ngFor="let item of testArray | testpipe : 2 as items">
    <div class="inner-wrap" style="border: 1px solid black;">
      <p>{{ item[0] }}</p>
      <p>{{ item[1] }}</p>
    </div>
  </ng-container>
</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.