Pipe Basics
Using pipes in your views is simple as using the pipe |
sign with the name of the pipe inside your bindings. To illustrate the point lets use the Angular 2's built in date pipe to transform our date object to a much readable format:
import { Component } from '@angular/core'
@Component({
selector: 'date-view',
template: `<p>Date: {{ created | date }}</p>`
})
export class DateViewComponent {
created = new Date(2016, 6, 2); // June 02, 2016
}
Passing parameters to pipes
Wouldn't it be nice to tell the date pipe to format the date in a particular format? Well yes, you can do this by passing parameters to the pipe. Here is an example that passes a format string as a parameter to the date pipe after the |
pipe symbol:
<p>Created on: {{ created | date:"MMMM/dd/yy HH:mm:ss" }} </p>
Chaining pipes
Multiple pipes can be chained to achieve desirable effect. For example if we wanted to show the date in all caps we could used the UppercasePipe
with the DatePipe
.
<p>Created on: {{ created | date:"MMMM/dd/yy HH:mm:ss" | uppercase }} </p>
Built in Pipes
Angular 2 comes with some built in pipes that offers basic functionality. These are the DatePipe that we just used. Other than that there is JsonPipe that is gives us nicely formatted Json. Then there are UpperCasePipe, LowerCasePipe and CurrencyPipe to name a few. You can see the complete list at Angular Docs.
As you can see these built in pipes offer basic functionality and unlike Angular 1 there are no built in filter or order by pipes. We'll discuss why these are not included in Angular 2 later.