A pipe receives data as an input and converts it into a specified output. Integrate the file named orderby.ts
into your /app
directory.
orderby.ts
//The Pipe class implements the transform method of the PipeTransform interface, which takes an input value and an optional array of parameters and returns the transformed value.
import { Pipe,PipeTransform } from "angular2/core";
//Indicate to Angular that this is a pipe by using the @Pipe decorator imported from the core Angular library.
@Pipe({
//The @Pipe decorator requires an object with a name property specifying the pipe's name for use in template expressions. It must be a valid JavaScript identifier. Our pipe is named orderby.
name: "orderby"
})
export class OrderByPipe implements PipeTransform {
transform(array:Array<any>, args?) {
if(array) {
let orderByValue = args[0]
let byVal = 1
if(orderByValue.charAt(0) == "!") {
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 newly added pipe by using:
import {OrderByPipe} from './orderby';
Then include
*ngFor="#article of articles | orderby:'id'"
in your template to sort articles by id in ascending order or
orderby:'!id'"
for descending order.
Add parameters to a pipe by appending the pipe name with a colon ( : ) followed by the parameter value
List the pipe in the pipes array within the @Component decorator like so: pipes: [ OrderByPipe ]
.
app.component.ts
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",
}]
}
}
For more information, visit my github page and read this post on my website