Miguel Miguel - 1 year ago 292
TypeScript Question

Global pipe in Angular 2

I want to make a pipe available in all the app. Acording with what I read in the Angular docs and internet, if I declare a pipe into the root module declaratios, it make's the pipe available in all the application. I have this AppModule code:

imports: [ BrowserModule, NavbarModule],
declarations: [ AppComponent, TranslatePipe],
bootstrap: [ AppComponent],
export class AppModule { }

And this for the child module:

imports: [ CommonModule],
declarations: [ NavbarMenuComponent],//<---Call the pipe in this component

export class NavbarModule { }

The pipe:

name: 'translate',
pure: false

export class TranslatePipe implements PipeTransform {
constructor() { }

transform(value: string, args: any[]): any {
return value + " translated";

But whe I call the pipe on the NavbarMenuComponent template it thows this error:

'The pipe "translate" could not be found'

If I declare the pipe in the child module declarations it works,but I need to make the pipe global, so when the app grows up, I don't need to declare this pipe(and other global pipes) in all modules. Is there a way to make the pipe global?

Answer Source

You need to add the module that contains the pipe (and has it in declarations: [] and exports: []) to imports: [...] of your current module, then it's available in the current module.

  imports:      [ CommonModule],
  declarations: [ TranslatePipe],
  exports:      [ TranslatePipe],
export class TranslateModule { }
  imports:      [ CommonModule, TranslateModule],
  declarations: [ NavbarMenuComponent]
export class NavbarModule { }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download