I would like to override the "date" pipe and enjoy the benefit of global access everywhere just like the built-in pipe--aka, avoid having to import and use pipes[] array in every component annotation. Is this possible?
Asked
Active
Viewed 5,844 times
3 Answers
16
Yes, you can use PLATFORM_PIPES
to add a custom pipe and name that pipe date
to hijack it.
@Pipe({
name : 'date' // Hijacks the 'date' pipe
})
class CustomDatePipe {
transform(val, args) {
return /* do something new with the value */;
}
}
@Component({
selector: 'my-app',
template : '{{mydate | date}}',
})
export class App {
mydate = Date.now();
}
// Provides the CustomDatePipe globally
bootstrap(App, [provide(PLATFORM_PIPES, {useValue: [CustomDatePipe], multi: true})]);
This way you won't have to add specify it every time in pipes
property in your components.
Here's a plnkr with an example working.

Eric Martinez
- 31,277
- 9
- 92
- 91
-
Do you know what needs to be done so pipes are also globally available within unit tests? – Vilmantas Baranauskas Jul 07 '16 at 13:22
5
Eric Martinez' answer works fine! Just keep in mind that PLATFORM_PIPES is deprecated in Angular4. Platform pipes in Angular4 are configured via app.modules:
/**
* `AppModule`
*/
@NgModule({
...
providers: [
...
CustomDatePipe
]
})

Katja Gräfenhain
- 71
- 2
- 5
-
And for testing (to answer Vilmantas Baranauskas' question): you can write a test for the Pipe itself and in your test explicitely invoke transform, e.g. new CustomDatePipe().transform(input) – Katja Gräfenhain Aug 03 '17 at 14:59
-
Deprecated! See https://stackoverflow.com/a/56020657/9224219 for solution – Datz Aug 18 '21 at 07:46
2
Yes, use PLATFORM_PIPES in following way
https://angular.io/docs/ts/latest/api/core/index/PLATFORM_PIPES-let.html
import {PLATFORM_PIPES} from '@angular/core';
import {OtherPipe} from './myPipe';
@Component({
selector: 'my-component',
template: `
{{123 | other-pipe}}
`
})
export class MyComponent {
...
}
bootstrap(MyComponent, [{provide: PLATFORM_PIPES, useValue: [OtherPipe], multi:true}]);

Regfor
- 8,515
- 1
- 38
- 51