In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:
$filter('date')(myDate, 'yyyy-MM-dd');
Is it possible to use pipes in services/components like this in Angular?
As usual in Angular, you can rely on dependency injection:
import { DatePipe } from '@angular/common';
class MyService {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
return this.datePipe.transform(date, 'yyyy-MM-dd');
}
}
Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:
providers: [DatePipe,...]
Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate function directly.
import { formatDate } from '@angular/common';
class MyService {
constructor(@Inject(LOCALE_ID) private locale: string) {}
transformDate(date) {
return formatDate(date, 'yyyy-MM-dd', this.locale);
}
}
Before Angular 5: Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).
If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem.
See this related question for a more detailed answer.
recommend using DI approach from other answers instead of this approach
You should be able to use the class directly
new DatePipe().transform(myDate, 'yyyy-MM-dd');
For instance
var raw = new Date(2015, 1, 12);
var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
expect(formatted).toEqual('2015-02-12');
Yes, it is possible by using a simple custom pipe. Advantage of using custom pipe is if we need to update the date format in future, we can go and update a single file.
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
transform(value: string) {
var datePipe = new DatePipe("en-US");
value = datePipe.transform(value, 'MMM-dd-yyyy');
return value;
}
}
{{currentDate | dateFormatPipe }}
You can always use this pipe anywhere , component, services etc
For example:
export class AppComponent {
currentDate : any;
newDate : any;
constructor(){
this.currentDate = new Date().getTime();
let dateFormatPipeFilter = new dateFormatPipe();
this.newDate = dateFormatPipeFilter.transform(this.currentDate);
console.log(this.newDate);
}
Don't forget to import dependencies.
import { Component } from '@angular/core';
import {dateFormatPipe} from './pipes'