angulartypescriptmodulesingle-page-applicationangular9

Error in importing a Angular custom pipe from a shared folder


I created a custom pipe from a shared folder to use it in component 1 (example: Applicant component) HTML, so I imported it to ApplicantModule. My goal, is for this pipe to be reusable in component 2 (example: Applicant component) so I also import this custom pipe to component's 2 module which is CoApplicantModule. After compiling I got console error.

enter image description here

When I tried to move the import statement of the custom pipe to SharedModule and tried the pipe from component 2, I got a console error. enter image description here

I would like to ask for your help since couldn't find the error for this one because I assume that it will work since SharedModule was also imported ApplicantModule and CoApplicantModule


Solution

  • You can't declare your pipe in more than one module . You can create a module for all your custom pipes, then just import it in all the components you need to use them.


    I usually create a directory in order to keep things organized. In this case pipes directory.

    pipes/pipes.module.ts

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { MyCustomPipe } from './myCustom.pipe';
    
    @NgModule({
      declarations: [MyCustomPipe],
      imports: [
        CommonModule
      ],
      entryComponents: [MyCustomPipe],
      exports: [MyCustomPipe]
    })
    export class PipesModule { }
    

    Now, you can reuse this in any of your components. For example:

    pages/home/home.module.ts

    ...
    import { PipesModule } from "../../pipes/pipes.module";
    ...
    
    @NgModule({
      imports: [
        ...,
        PipesModule
      ],
      declarations: [HomePage]
    })
    export class HomePageModule {}
    

    Now, they are already available here.

    pages/home/home.page.html

    ...
    <p>{{ something | myCustomPipe }}</p>
    ...
    

    As @JimiLoe commented, entryComponents is deprecated and no longer needed since Angular v9.

    You can find more info in