Using Angular 2 built-in pipes within the Typescript/Javascript

Angular comes with a few built-in pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe and PercentPipe. They are all immediately available for use in any template like so:

(from Angular 2 API Reference on DatePipe)

{{ dateObj | date }} // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }} // output is '9:43 PM'
{{ dateObj | date:'mmss' }} // output is '43:11'

But it requires a few more lines to have access within the actual Javascript/Typescript, so you can do something like this:

this.datePipe.transform(this.dateObj); // output is 'Jun 15, 2015'
this.datePipe.transform(this.dateObj, 'medium'); // output is 'Jun 15, 2015, 9:43:11 PM'
this.datePipe.transform(this.dateObj, 'shortTime'); // output is '9:43 PM'
this.datePipe.transform(this.dateObj, 'mmss');  // output is '43:11'

Within your main module, import the DatePipe from @angular/common and add it to the providers property.

app.module.ts (excerpt)


import { DatePipe } from '@angular/common'; @NgModule({ providers: [ DatePipe ] })

booking.service.ts

This is the file you want to use DatePipe in (so let’s take my case of booking.service.ts)


import { DatePipe } from '@angular/common'; export class BookingService { someFunction(){ return this.datePipe.transform(this.dateObj, 'dd/MM/yyyy'); // output is 15/06/2015 } constructor( private datePipe: DatePipe ) {} }