Search code examples
angularmoduleangular-componentsangular-module

Angular: How to share a component between different components in different modules and vice versa


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?


Solution

  • 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.