8

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

2
  • 1
    This seems misleading, where is toUpperCase being called? Not anywhere in what you've posted. Commented Dec 13, 2016 at 22:54
  • I know, the error does not give much help, this is why I think maybe the pipe is causing it. without the pipe then I get no error. Commented Dec 13, 2016 at 23:10

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

Comments

10

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.