Angular 'unexpected pipe imported by module' error

Viewed 20428

I have created a custom pipe that uses the DecimalPipe transform() method. I am using this pipe inside one of feature modules and I have to add both of those pipes to providers: [] (because MyCustomPipe uses DecimalPipe), like so:

index.ts:

@NgModule({
    imports: [
        MaterialModule,
        SharedModule
    ],
    declarations: [
        ...
    ],
    providers: [
        DecimalPipe,
        MyCustomPipe
    ...

My goal however is to not have to add DecimalPipe to a feature module in this way and have that dependence between MyCustomPipe and DecimalPipe 'hidden', so that who ever is consuming MyCustomPipe can just worry about importing MyCustomPipe from SharedModule. I tried to resolve this by trying to follow the SharedModule pattern and have the DecimalPipe exported from SharedModule (as I did with MyCustomPipe), like so:

shared.module.ts:

...import { DecimalPipe } from '@angular/common';

...export * from '../pipes/index';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        HttpModule,
        DecimalPipe
    ],
    declarations: [
        LoginComponent,
        ErrorComponent,
        MyCustomPipe,
    ],
    exports: [
        CommonModule,
        HttpModule,
        LoginComponent,
        ErrorComponent,
        DecimalPipe,
        MyCustomPipe
    ]
})

However, when I try to do this I get the error "Error: (SystemJS) Unexpected pipe 'DecimalPipe' imported by the module 'SharedModule'. Please add a @NgModule annotation." . Now, I could add DecimalPipe to declarations: [] in SharedModule, but then I get the error warning me that DecimalPipe is declared both in SharedModule and CommonModule. I think this stems from my lack of understanding of the SharedModule pattern described in the docs. I am not 100% if this even is the right approach, as I have never tried to share a custom pipe that uses a build-in Angular pipe with feature modules.

3 Answers

Updated

Just for safe note: add pipe-class in declarations and pipe-module in imports

@NgModule({
  declarations: [
    CustomDatePipe
  ],
  imports: [
    CustomDateModule
  ]
})
export class AppModule { }
Related