14

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?

3 Answers 3

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.

1
  • Do you know what needs to be done so pipes are also globally available within unit tests? Jul 7, 2016 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
    ]
})
2
  • 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) Aug 3, 2017 at 14:59
  • Deprecated! See stackoverflow.com/a/56020657/9224219 for solution
    – Datz
    Aug 18, 2021 at 7: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}]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.