Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  40] [ 1]  / answers: 1 / hits: 99836  / 8 Years ago, sun, april 3, 2016, 12:00:00

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.


More From » angular

 Answers
13

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)


[#62714] Thursday, March 31, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zoiel

Total Points: 692
Total Questions: 90
Total Answers: 89

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
zoiel questions
Mon, Jun 10, 19, 00:00, 5 Years ago
Thu, Mar 21, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;