Angular 2中的全局管道

时间:2016-10-24 13:25:32

标签: angular typescript

我想在所有应用中提供管道。根据我在Angular文档和互联网中读到的内容,如果我在根模块声明中声明了一个管道,那么它就是所有应用程序中的管道。我有这个AppModule代码:

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

这对于儿童模块:

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

export class NavbarModule { }

管道:

@Pipe({
    name: 'translate',
    pure: false
})

export class TranslatePipe implements PipeTransform {
    constructor() { }

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

但是当我在NavbarMenuComponent模板上调用管道时,它会抛出此错误:

  

'管道“翻译”无法找到'

如果我在子模块声明中声明管道它可以工作,但我需要使管道全局,所以当应用程序成长时,我不需要在所有模块中声明这个管道(和其他全局管道) 。有没有办法让管道全球化?

1 个答案:

答案 0 :(得分:8)

您需要将包含管道的模块添加到当前模块的declarations: [] exports: []imports: [...]},然后才能在当前模块中可用。

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