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

后端 未结 3 697
太阳男子
太阳男子 2021-01-11 10:49

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 i

相关标签:
3条回答
  • 2021-01-11 11:19

    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}]);
    
    0 讨论(0)
  • 2021-01-11 11:21

    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
        ]
    })
    
    0 讨论(0)
  • 2021-01-11 11:27

    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.

    0 讨论(0)
提交回复
热议问题