A pipe takes in data as input and transforms it to a desired output.
Add this pipe file:orderby.ts
inside your /app
folder .
//The pipe class implements the PipeTransform interface's transform method that accepts an input value and an optional array of parameters and returns the transformed value.
import { Pipe,PipeTransform } from "angular2/core";
//We tell Angular that this is a pipe by applying the @Pipe decorator which we import from the core Angular library.
@Pipe({
//The @Pipe decorator takes an object with a name property whose value is the pipe name that we'll use within a template expression. It must be a valid JavaScript identifier. Our pipe's name is orderby.
name: "orderby"
})
export class OrderByPipe implements PipeTransform {
transform(array:Array<any>, args?) {
// Check if array exists, in this case array contains articles and args is an array that has 1 element : !id
if(array) {
// get the first element
let orderByValue = args[0]
let byVal = 1
// check if exclamation point
if(orderByValue.charAt(0) == "!") {
// reverse the array
byVal = -1
orderByValue = orderByValue.substring(1)
}
console.log("byVal",byVal);
console.log("orderByValue",orderByValue);
array.sort((a: any, b: any) => {
if(a[orderByValue] < b[orderByValue]) {
return -1*byVal;
} else if (a[orderByValue] > b[orderByValue]) {
return 1*byVal;
} else {
return 0;
}
});
return array;
}
//
}
}
In your component file (app.component.ts) import the pipe that you just added using: import {OrderByPipe} from './orderby';
Then, add *ngFor="#article of articles | orderby:'id'"
inside your template if you want to sort your articles by id in ascending order or orderby:'!id'"
in descending order.
We add parameters to a pipe by following the pipe name with a colon ( : ) and then the parameter value
We must list our pipe in the pipes array of the @Component decorator. pipes: [ OrderByPipe ]
.
import {Component, OnInit} from 'angular2/core';
import {OrderByPipe} from './orderby';
@Component({
selector: 'my-app',
template: `
<h2>orderby-pipe by N2B</h2>
<p *ngFor="#article of articles | orderby:'id'">
Article title : {{article.title}}
</p>
`,
pipes: [ OrderByPipe ]
})
export class AppComponent{
articles:Array<any>
ngOnInit(){
this.articles = [
{
id: 1,
title: "title1"
},{
id: 2,
title: "title2",
}]
}
}
More info here on my github and this post on my website