Angular2 sorting array for displaying in *ngFor in

2020-07-09 03:53发布

问题:

I am looping through all the posts

<li *ngFor="let post of posts">

When displaying the date for each post I do:

{{post.date | date:'yyyy-MM-dd HH:mm:ss'}}

What I want to do is display all the posts in order of newest first.

I have 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 it does not work. I get the error:

TypeError: Cannot read property 'toUpperCase' of undefined ("
[ERROR ->]*ngFor="let post of posts | order-by-pipe">

Any help would be welcome, thanks

回答1:

When you use order-by-pipe as the selector it is attempting to find the variables order by and pipe and do who knows what with them.

Changing the name: in your pipe to orderByPipe resolves the issue.

That was weird.

Here's a demo of the same code, different name: http://plnkr.co/edit/BXkrPqeMYuJMhkx94i6M?p=preview



回答2:

The Angular team recommends against using pipes for sorting in Angular 2, and dropped this feature from AngularJS purposely. As detailed on https://angular.io/guide/pipes:

Angular doesn't offer such pipes because they perform poorly and prevent aggressive minification... Filtering and especially sorting are expensive operations. The user experience can degrade severely for even moderate-sized lists when Angular calls these pipe methods many times per second. filter and orderBy have often been abused in AngularJS apps, leading to complaints that Angular itself is slow... The Angular team and many experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself.

See a similar discussion at https://stackoverflow.com/a/43092380/3211269