How can I apply a quantity limit to *ngFor?

JavascriptAngular

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHossam MouradView Question on Stackoverflow
Solution 1 - JavascriptsqwkView Answer on Stackoverflow