73

Since the Limit filter is gone from Angular 2+, how can I apply a limit for a simple *ngFor statement?

<div *ngFor="#tweet of singleCategory">
  {{ tweet }}
</div>

I don't want the *ngFor statement to loop through all the elements of singleCategory, I want to limit it to just 2 results. I believe that it could be done with Custom Pipes but I don't know how to implement it.

Thank you.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Hossam Mourad
  • 4,369
  • 4
  • 26
  • 22

1 Answers1

115

You can either apply an ngIf on the element using the index:

<div *ngFor=" let tweet of singleCategory;  let i=index">
    <div *ngIf="i<2">
        {{tweet}}
    </div>
</div>

If you don't want the wrapping div, check out template syntax:

<ng-template ngFor let-tweet [ngForOf]="singleCategory" let-i="index">
    <div [ngIf]="i<2">
        {{tweet}}
    </div>
</ng-template>

Preferably you first/instead filter the elements in your component using filter to prevent unnecessary loops when displaying your data:

public get singleCategory() {
   return this.categories.filter((item, index) => index > 2 )
}

There is also the option of creating a pipe. (See the linked duplicate)

sqwk
  • 2,649
  • 1
  • 28
  • 42
  • 1
    Shouldn't that last one be return index > 2 – Mathijs Segers Apr 25 '16 at 08:55
  • 5
    as of today the template syntax [is deprecated](https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta17-2016-04-28), you should use `let tweet` instead of `#tweet` – pietro909 Jun 01 '16 at 10:11
  • 91
    Just one more option: `
    `
    – prespic Sep 14 '16 at 08:23
  • 12
    Now in Angular4+ ` – developer033 Apr 13 '17 at 02:11
  • Just if anyone explores an error with updating the model with the slice option, you could return a new array and splice this one: `
    `
    – Stefan Rein Jun 20 '17 at 05:33
  • 1
    but.... if the length of the collection is 100,000, just because you `*ngIf` the inner content, won't angular still add 100,000 of the `div` to the document? Seems like this is not a good answer. – frosty Dec 27 '17 at 21:42
  • 8
    I like this solution: https://stackoverflow.com/questions/37818677/how-can-i-limit-ngfor-repeat-to-10-items-in-angular-2 – georgeos Dec 28 '17 at 16:57
  • 2
    I find @georgeos gives the best solutions – Stevanicus Aug 02 '18 at 10:59
  • @prespic functions in your template (`.slice(...`) are executed every change detection. Unless you're using `OnPush` your proposed option can cause performance issues. [more info here](https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496) – adamdport Apr 09 '20 at 16:02