Miguel Miguel - 1 month ago 34
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:

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


And this for the child module:

@NgModule({
imports: [ CommonModule],
declarations: [ NavbarMenuComponent],//<---Call the pipe in this component
})

export class NavbarModule { }


The pipe:

@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

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.

@NgModule({
  imports:      [ CommonModule],
  declarations: [ TranslatePipe],
  exports:      [ TranslatePipe],
})
export class TranslateModule { }
@NgModule({
  imports:      [ CommonModule, TranslateModule],
  declarations: [ NavbarMenuComponent]
})
export class NavbarModule { }
Comments