angular 5 , orderBy asc/desc

user636312 picture user636312 · Mar 25, 2018 · Viewed 15.7k times · Source

Is there an option to change sorting by asc/desc in orderBy pipe?

The array:

this.testArr = [{name: 'bbb', id: '1'}, {name: 'ccc', id: '2'}, {name: 'aaa', id: '0'}];

In HTML:

<ul><li *ngFor="let item of testArr | orderBy: 'id' : true"><div>{{item.id}}</div></li></ul>

Replacing the 'true' to 'false'/'asc'/'desc' did not work. The required output should be: 0, 1, 2 and by the other parameter: 2, 1, 0.

Thank you.

Answer

Horse picture Horse · May 2, 2018

The angular guide recommends not using pipes due to performance and minification issues - https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

The preferred method is to have a filter / sort method in the component

sortAccounts(prop: string) {
    const sorted = this.accounts.sort((a, b) => a[prop] > b[prop] ? 1 : a[prop] === b[prop] ? 0 : -1);
    // asc/desc
    if (prop.charAt(0) === '-') { sorted.reverse(); }
    return sorted;
}

Then in the component view

<li *ngFor="let a of sortAccounts('id')">

or

<li *ngFor="let a of sortAccounts('-id')">