<...">

Angular 2. How to apply orderBy?

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 an orderBy filter to order strings by my filter. But how can I make orderBy in Angular 2 in the same way? Thanks.

+6
source share
3 answers

To do this, you need to implement your own channel. This corresponds to creating a class decorated with @Pipe. Here is an example. Its conversion method will actually process the list, and you can sort it as you wish:

 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; } } 

Then you can use this channel as described below in the expressions. For example, in ngFor. Do not forget to specify your channel in the pipes attribute of the component in which you use it:

 @Component({ (...) template: ` <li *ngFor="list | orderby"> (...) </li> `, pipes: [ OrderByPipe ] }) (...) 
+12
source

If you use lodash , your pipe might 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 the full power of the method:

 <li *ngFor="let product of products | orderBy: 'price': 'desc'"> {{product.name}} </li> 
+9
source

Thank you for your responses. I wrote the working 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 considers the order direction of DESC or ASC. Using:

 <tr *ngFor="#participant of participants | orderBy: '-score'; #i = index"> 
+4
source

All Articles