-1

How to share a component between different components in different modules share the components in the different modules with the shared component.

I have four modules. Module A with component A, Module B with component B, Module C with component C, and Module D with component D. Modules B, C and D each import Module A in order to access component A. But there is an issue, component A needs the respective components that use it. For example component A needs component B when being used by component B.

Is there a way to make it work without making the modules B, C and D each have their own copy of component A?

YulePale
  • 6,688
  • 16
  • 46
  • 95
  • is it not possible for you to import A and B in the Same Module so that they can communicate with each other – Fahad Rehman Jul 04 '20 at 15:35
  • @FahadRehman Thanks. I understand that. I was looking for another way to achieve my objective. The accepted answer has shown me that other way. – YulePale Jul 05 '20 at 05:59

1 Answers1

3

Its a common requirement. Here let me explain it a little.

Angular allows one component to be declared in one and only one module. And if that component is required in another module, you'll have to import that module in the imports array of the module that needs that component.

Now if Component A is in Module A, and Component B in Module B and both needs each other, and you import Module A in Module B, and Module B in Module A, then you fall in circular reference trap.

To resolve this issue, you'll have to introduce a new module, and declare all such components in this new module, and let this new module to be imported in the modules that need the components.

Lets say my this new module name is LoaderSharedModule, it would look like this

@NgModule({
  imports: [
  ],
  declarations: [Component1, Component2, Component3],
  exports: [Component1, Component2, Component3]
})
export class LoaderSharedModule { }

The modules would import this module to start using Component1,2,3.. like this

@NgModule({
  imports: [
    LoaderSharedModule
  ],
})
export class Module1 { }

@NgModule({
  imports: [
    LoaderSharedModule
  ],
})
export class Module2 { }

@NgModule({
  imports: [
    LoaderSharedModule
  ],
})
export class Module3 { }

Thanks.

Obaid
  • 2,563
  • 17
  • 15
  • 1
    I honestly thought there was no way. I was about to create duplicate components. I am glad I asked. Thanks. – YulePale Jul 05 '20 at 05:57