Angular2 sorting array to display in * ngFor in html
I view all posts
<li *ngFor="let post of posts"> When displaying the date for each message, I do:
{{post.date | date:'yyyy-MM-dd HH:mm:ss'}} What I want to do is display all the messages in the order they appear first.
I tried using a pipe like:
<li *ngFor="let post of posts | order-by-pipe"> import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'order-by-pipe' }) export class OrderByPipe implements PipeTransform{ transform(array: Array<string>, args: string): Array<string> { if(!array || array === undefined || array.length === 0) return null; array.sort((a: any, b: any) => { if (a.date < b.date) { return -1; } else if (a.date > b.date) { return 1; } else { return 0; } }); return array; } } But that will not work. I get an error message:
TypeError: Cannot read property 'toUpperCase' of undefined (" [ERROR ->]*ngFor="let post of posts | order-by-pipe"> Any help would be appreciated, thanks
When you use order-by-pipe as a selector, it tries to find the order by and pipe variables, and who knows what is wrong with them.
Changing name: in your channel to orderByPipe fixes the problem.
That was weird.
Here is a demo of the same code, another name: http://plnkr.co/edit/BXkrPqeMYuJMhkx94i6M?p=preview
The Angular team recommends not using pipes for sorting in Angular 2, and missed this feature specifically for AngularJS. As described in https://angular.io/guide/pipes :
Angular does not offer such pipes because they do not work well and prevent aggressive minimization ... Filtering and especially sorting are expensive operations. The user interface can be severely degraded for even moderate-sized lists when Angular calls these pipe methods many times per second. the filter and orderBy were often abused in AngularJS applications, leading to complaints that Angular itself is slow ... The Angular team and many experienced Angular developers strongly recommend moving the filtering and sorting logic into the component by itself.
See a similar discussion at fooobar.com/questions/48433 / ...