How to declare a pipe globally to use in different modules?

In Angular a good technique for sharing common directives, components, pipes, etc. is to use a so called shared module.

Those modules declare and export common parts, to make them usable for any of your other modules.

The fundamentals section of the angular documentation is a very good read about shared modules.

Let’s take as example your currConvert pipe.

  • Declare new NgModule called ApplicationPipesModule

  • Add the pipe to the declarations and exports arrays of the NgModule-decorator metadata

  • Add any modules that may be required for your pipe to work to the
    imports array

    // application-pipes.module.ts
    // other imports
    import { CurrConvertPipe } from './{your-path}';
    
    @NgModule({
      imports: [
        // dep modules
      ],
      declarations: [ 
        CurrConvertPipe
      ],
      exports: [
        CurrConvertPipe
      ]
    })
    export class ApplicationPipesModule {}
    
  • import the created ApplicationPipesModule module into the modules where your pipe is going to be used, by adding it to the imports array

    // my-module1.module.ts
    // other imports
    import { ApplicationPipesModule } from './{your-path}';   
    
    @NgModule({
     imports: [
       // other dep modules
       ApplicationPipesModule
     ],
     declarations: [],
     exports: []
    })
    export class MyModule1 {}
    

Leave a Comment