Simon
Simon

Reputation: 2538

Loop through ngFor and if the index mod(%) 10 is 0 show seperator

I have a component called post and I'm looping through it to show all of the posts that are within an array.

What I'd like to do is separate the post so that after each 10th post it shows a "page separator", something that just says Page X. So like:

post
post
...
post #10
-- Page 2 --
post
post
...
post #20
-- Page 3 --

Here is my HTML:

<post *ngFor="let post of postFeed.reverse()" [postData]="post"></post>
<div *ngFor="let post of postFeed.reverse(); let i = index" [hidden]="i % 10 != 0" class="pageIndicator">
  <div class="pageNumb">Page {{(i/10)+1}}</div>
</div>

but it seems like you cannot do i % 10 != 0 inside the HTML.. any ideas?

It seems like it would be simple, but I can't wrap my head around it.. Thanks!

Upvotes: 1

Views: 646

Answers (2)

Daniel Macak
Daniel Macak

Reputation: 17063

There are several problems with the code.

First of all, you are calling reverse() twice in your template. The reverse method mutates the original array so you actually reverse what you have reversed - not sure if this is what you wanted.

Secondly your template code can result only in uninterrupted list of posts with displayed page indicators at the end, because you first iterate through the array and generate posts, and only after last iteration those page indicators start being iterated and generated.

You can choose easier approach in your template - come up with one container element on which the *ngFor iteration will happen and inside the posts will be with occasional page indicators.

<div *ngFor="let post of postFeed; let i = index">
  <post [postData]="post"></post>
  <div class="post-indicator" *ngIf="i > 0 && i % 10 == 0">
    Page {{i / 10 + 1}}
  </div>
</div>

If you don't want to use extra wrapping div, use ng-container - it will generated no element in the result document.

As you can see, you can use % in your templates. See more on what you can use in template expressions here in Angular docs.

If you want to see example I have compiled, have a look at it here.

Upvotes: 1

birwin
birwin

Reputation: 2684

You might try adding a function to your component that checks for mod = 0 and using an *ngIf to display result

Your component would have something like this:

isPageBreak(index) {
    if (index > 0 && index % 10 === 0) {
        return true;
    }
    return false;
}

and then your view would look something like this:

<div *ngFor="let post of postFeed.reverse(); let i = index">
  <post [postData]="post"></post>
  <div *ngIf="isPageBreak(i)" class="pageIndicator">
    <div class="pageNumb">Page {{(i/10)+1}}</div>
  </div>
</div>

Note... I didn't test any of this code. Just typed it in, so it may not work without tweaks.

Upvotes: 0

Related Questions