In Angular2 you can use „pipes“ (in earlier versions called „filters“) to adjust data bindings to given situations. Then name comes from the „pipe symbol“ (|) that is also known from Unix/Linux command shells to manipulate data streams. In Angular 2, the most common pipes are „date“ (date format rendering), „async“ (asynchronous data binding of Observables) and String-manipulating pipes like „uppercase“ / „lowercase“. I will focus on the „date“ pipe in this article.
How do pipes work
Basically, they take data from a binding of the component and return another value, given by a mapping function. To use them in an expression, just write the data exporession, then the pipe symbol, then then name of the pipe, e.g.
1 |
{{ name | uppercase }} |
The date pipe
In the case of the „date“ pipe, imagine you have a property of your component that is of type Date:
1 2 3 4 5 6 7 8 9 10 11 |
import {Component} from "@angular/core" @Component({ selector: "fnb-dateexample", templateUrl: "dateexample.html" }) export class DateExampleComponent { public myDate: Date = new Date(2016, 2, 27, 15, 0, 31) } |
Now what happens, if you just print the date out in the template:
1 |
<p>Date Example: {{myDate}}</p> |
The result will look something like this: „Date Example: Sun Mar 27 2016 15:00:31 GMT+0200“. Doesn’t look so nice, does it?
Now what we want is a proper date formatter. This is what the date pipe is for:
1 |
<p>Date Example: {{myDate | date}}</p> |
And now it will print like this: „Date Example: Mar 27, 2016“.
Configuring the pipe
But wait, what if we don’t only want to display the date, but also the time? Fortunately, pipes also can be given parameters, in the case of the date pipe, the date format to use. So to display the correct date and time, we can pass the date format appended by a colon:
1 |
Date Example: {{myDate | date:"yMMMdjms"}} |
Parameters after the colon are then added as parameters to the pipe class. The result will look like this: „Mar 27, 2016, 3:00:31 PM“