2016-10-24 9 views
3

すべてのアプリケーションでパイプを使用したいと思っています。私がAngularのドキュメントとインターネットで読んだところによると、ルートモジュールdeclaratiosにパイプを宣言すると、それはすべてのアプリケーションで利用可能なパイプになります。グローバルパイプin角2

@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"; 
    } 
} 

しかし、WHE、私はそれがこれをthows NavbarMenuComponentテンプレートにパイプを呼び出し、子モジュールの

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

そして、この:私はこのAppModuleコードを持っていますエラー:

'The pipe "translate" could not be found'

子モジュールの宣言でパイプを宣言すると機能しますが、パイプをグローバルにする必要があります。アプリケーションが大きくなると、このパイプ(および他のグローバルパイプ)をすべてのモジュールで宣言する必要はありません。パイプをグローバルにする方法はありますか?あなたの現在のモジュールのimports: [...]へのパイプが含まれています(とdeclarations: []exports: []でそれを持っている)モジュールを追加する必要が

答えて

5

は、それが現在のモジュールで利用可能です。

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

私はあなたの応答でコードをupdtedは、私がAppModuleの輸出にパイプを添加し、次いで、「NavBarModule」輸入にAppModuleを輸入し、今では別のエラーがスローされます:「Usepectedをモジュール "NavbarModule"によってインポートされた値 "undefined"。 – Miguel

+0

他のモジュールで 'AppModule'をインポートするのではなく、パイプの共有機能モジュールを作成する方がよいでしょう。モジュール(あなたの場合 'AppModule'は' TranslatePipe'をエクスポートする必要があります。) –

+0

私の答えを更新しました –