9

I have a piece of code.

<table class="table table-bordered table-condensed" cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Score</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="#participant of participants; #i = index">
            <td>{{i+1}}</td>
            <td>{{participant.username}}</td>
            <td>{{participant.score}}</td>
        </tr>
    </tbody>
</table>

In Angular 1 i have orderBy filter to order rows by my filter. But how can i do orderBy in Angular 2 the same way ? Thank you.

Edward
  • 589
  • 1
  • 9
  • 18
  • 3
    Possible duplicate of [Angular 2 OrderBy Pipe](http://stackoverflow.com/questions/35158817/angular-2-orderby-pipe) See also https://angular.io/docs/ts/latest/guide/pipes.html for pipes in general – Günter Zöchbauer Feb 17 '16 at 15:42

4 Answers4

20

If you are using lodash your pipe can be like this:

import { Pipe, PipeTransform } from '@angular/core';
import { orderBy } from 'lodash';

@Pipe({
  name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
  transform = orderBy;
}

And then you can use all the power of the method:

<li *ngFor="let product of products | orderBy: 'price': 'desc'">
  {{product.name}}
</li>
Alex Chuev
  • 693
  • 5
  • 17
15

You need to implement a custom pipe for this. This corresponds to create a class decorated by @Pipe. Here is a sample. Its transform method will actually handle the list and you will be able to sort it as you want:

import { Pipe } from "angular2/core";

@Pipe({
  name: "orderby"
})
export class OrderByPipe {
  transform(array: Array<string>, args: string): Array<string> {
    array.sort((a: any, b: any) => {
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}

You can then use this pipe as described below in expressions. For example in an ngFor. Don't forget to specify your pipe into the pipes attribute of the component where you use it:

@Component({
  (...)
  template: `
    <li *ngFor="list | orderby"> (...) </li>
  `,
  pipes: [ OrderByPipe ]
})
(...)
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
4

Thank you for your answers. I have written workable code below:

@Pipe({name: 'orderBy'})

export class orderBy implements PipeTransform {
    transform(obj: any, orderFields: string): any {
        orderFields.forEach(function(currentField) {
            var orderType = 'ASC';

            if (currentField[0] === '-') {
                currentField = currentField.substring(1);
                orderType = 'DESC';
            }

            obj.sort(function(a, b) {
                if (orderType === 'ASC') {
                    if (a[currentField] < b[currentField]) return -1;
                    if (a[currentField] > b[currentField]) return 1;
                    return 0;
                } else {
                    if (a[currentField] < b[currentField]) return 1;
                    if (a[currentField] > b[currentField]) return -1;
                    return 0;
                }
            });

        });
        return obj;
    }
}

This code consider order direction DESC or ASC. The usage:

<tr *ngFor="#participant of participants | orderBy: '-score'; #i = index">
Edward
  • 589
  • 1
  • 9
  • 18
  • 5
    You should not do this with pipes: https://angular.io/docs/ts/latest/guide/pipes.html#!#no-filter-pipe – Max Aug 09 '16 at 11:25
  • @JobVermeulen is correct. According to the Angular documentation, for performance and to avoid conflicts in minification, pipes should not be used for sorting and orderby. Those things should be handled in components. – Danny Jul 06 '17 at 05:35
0

The most recent lib that I know

https://www.npmjs.com/package/ngx-pipes

const numbers = [2, 1, 3];
 
const obj = [
  {id: 4, name: 'Dave', amount: 2},
  {id: 2, name: 'Michael', amount: 2},
  {id: 3, name: 'Dan', amount: 1},
  {id: 1, name: 'John', amount: 1}
];
 
const deepObj = [
  {id: 1, name: 'John', amount: 1337, deep: {prop: 4}},
  {id: 2, name: 'Michael', amount: 42, deep: {prop: 2}},
  {id: 3, name: 'Dan', amount: 1, deep: {prop: 1}},
  {id: 4, name: 'Dave', amount: 2, deep: {prop: 3}}
];

<!-- Returns array ordered by value -->
<p>{{ numbers | orderBy }}</p>  <!-- Output: [1, 2, 3] -->
<p>{{ numbers | orderBy: '-' }}</p>  <!-- Output: [3, 2, 1] -->
 
<!-- Returns array ordered by value of property -->
<p>{{ deepObj | orderBy: 'amount' }}</p>  
<!-- Output: [{id: 3, ...}, {id: 4, ...}, {id: 2, ...}, {id: 1, ...}] -->
<p>{{ deepObj | orderBy: '-amount' }}</p>  
<!-- Output: [{id: 1, ...}, {id: 2, ...}, {id: 4, ...}, {id: 3, ...}] -->
 
<!-- Returns array ordered by value of deep property -->
<p>{{ deepObj | orderBy: 'deep.prop' }}</p>  
<!-- Output: [{id: 3, ...}, {id: 2, ...}, {id: 4, ...}, {id: 1, ...}] -->
<p>{{ deepObj | orderBy: '-deep.prop' }}</p>  
<!-- Output: [{id: 1, ...}, {id: 4, ...}, {id: 2, ...}, {id: 3, ...}] -->
 
<!-- Returns array ordered by mutliple properties -->
<p>{{ obj | orderBy: ['amount', 'id'] }}</p>  
<!-- Output: [{id: 1, ...}, {id: 3, ...}, {id: 2, ...}, {id: 4, ...}] -->
Rafael Pizao
  • 742
  • 8
  • 21