This might be a question for many of you angularjs developers who have moved to the Angular recently and trying to find your way around the new framework.
If you remember in angularjs we have
$filter which is equivalent to
Pipe in Angular. There are filters for formatting data in template (eg: date, number, money) and filters for sorting. All provided by angularjs.
Moving to Angular we use pipes for similar reasons. Formatting date, number and there are pipes provided by framework for many of these use cases but no pipes for sorting(ordering) and filtering.
If you Google for Angular orderBy pipe you will find many implementations that you can happily copy and use in your project. That will show those forgetful developers in Angular team.
Just let’s ask the question again before copying from stackoverflow.
Did guys at Angular really forget about creating orderBy pipe?
You may think so but that’s not the case.
If you try a little further and search for it in Angular documentation, you will come across this page.
It’s an interesting read. Gist of it is that it’s not a good idea to do sorting or filtering using a pipe in template. It has performance overhead when used across the application. Making your app slow and you won’t get the best out of build optimization magic that Angular does.
The solution is obvious and easy to achieve. Do sorting, filtering and any sort of data manipulation in your component code and let your template just show the ready to display values or lists.
Putting too much logic in template is a bad idea. Not only with orderBy pipes but calling functions in template is also a bad for your application performance.
This is mainly because of the way Angular rendering engine interprets your template.
You should avoid the above code because the method will be called every time change detection runs.
It’s better to call the method in component’s code. For example in the constructor(), ngOnInit(), or an event handler then assign the result to a property and from the template bind to that property.
Calling event handlers is fine of course
<button (click)="myElegantMethod(item)">click me</button>
Event handler will only trigger when the event is emitted. So we are good.