Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply a quantity limit to *ngFor? [duplicate]

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.

like image 259
Hossam Mourad Avatar asked Apr 03 '16 16:04

Hossam Mourad


1 Answers

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)

like image 160
sqwk Avatar answered Sep 30 '22 01:09

sqwk