Error in importing a Angular custom pipe from a shared folder
Asked Answered
P

2

5

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

Psychographer answered 22/12, 2020 at 14:56 Comment(0)
S
10

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

Shagbark answered 22/12, 2020 at 16:49 Comment(2)
In this example I'm talking about just one module, but you can always create different modules for different pipes.Shagbark
Meanwhile, attribute 'entryComponents' is obsolete and can be removed.Jeannajeanne
M
1

Your error says you that you have declared pipe in 2 modules. You got solution in your error message. You can create another module where you add your pipe to declarations and then you export it in exports and instead of "importing" your pipe by declarations you just import created module in imports.

Mintamintage answered 22/12, 2020 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.