Alan Lindsay
Alan Lindsay

Reputation: 165

Is it possible to override the built-in Angular 2 pipes so they can be used globally?

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?

Upvotes: 14

Views: 6365

Answers (3)

Katja Gräfenhain
Katja Gräfenhain

Reputation: 81

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
    ]
})

Upvotes: 5

Regfor
Regfor

Reputation: 8101

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}]);

Upvotes: 2

Eric Martinez
Eric Martinez

Reputation: 31787

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.

Upvotes: 16

Related Questions