Table of contents
No headings in the article.
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 the 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 the Angular team.
Just let’s ask the question again before copying from stackoverflow.
Did guys at Angular 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.
https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
It’s an interesting read. The gist of it is that it’s not a good idea to do sorting or filtering using a pipe in the 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 the template is a bad idea. Not only with orderBy pipes but calling functions in the template is also bad for your application performance.
This is mainly because of the way Angular rendering engine interprets your template.
<div>{{myElegantMethod(item)}}</div>
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 variable and from the template bind to that variable.
Calling event handlers is fine of course
<button (click)="myElegantMethod(item)">click me</button>
The event handler will only trigger when the event is emitted. So we are good.