Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 sort and filter

In Angularjs 1 it is possible to sort and filter the following way:

<ul ng-repeat="friend in friends | filter:query | orderBy: 'name' ">    <li>{{friend.name}}</li> </ul> 

But I could not find any examples of how to do this in Angularjs 2.0. My question is how to sort and filter in Angularjs 2.0? If it is still not supported, does anyone know when or if it will be put into Angularjs 2.0?

like image 414
alexsoftware Avatar asked Oct 01 '15 07:10

alexsoftware


2 Answers

This isn't added out of the box because the Angular team wants Angular 2 to run minified. OrderBy runs off of reflection which breaks with minification. Check out Miško Heverey's response on the matter.

I've taken the time to create an OrderBy pipe that supports both single and multi-dimensional arrays. It also supports being able to sort on multiple columns of the multi-dimensional array.

<li *ngFor="let person of people | orderBy : ['-lastName', 'age']">{{person.firstName}} {{person.lastName}}, {{person.age}}</li> 

This pipe does allow for adding more items to the array after rendering the page, and still sort the arrays with the new items correctly.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

EDIT: Added new demo to http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby

EDIT 2: Updated ngFor to new syntax

like image 121
Cory Shaw Avatar answered Nov 10 '22 03:11

Cory Shaw


It is not supported by design. The sortBy pipe can cause real performance issues for a production scale app. This was an issue with angular version 1.

You should not create a custom sort function. Instead, you should sort your array first in the typescript file and then display it. If the order needs to be updated when for example a dropdown is selected then have this dropdown selection trigger a function and call your sort function called from that. This sort function can be extracted to a service so that it can be re-used. This way, the sorting will only be applied when it is required and your app performance will be much better.

like image 37
trees_are_great Avatar answered Nov 10 '22 03:11

trees_are_great