Search code examples
angulartypescriptshared-module

Angular shared module exports component imported by another module


I have 3 modules. Lets call them StoreModule, BookModule, PaperModule. Store sells books, so store uses book. Book consist of paper, so uses paper, the exact same paper as store uses. And store uses paper as well. Here comes the problem! Now the real life example for this in angular:

paper.module.ts

import { NgModule } from '@angular/core';
import { PaperComponent } from './paper.component';

@NgModule({
  declarations: [
    PaperComponent
  ],
  exports: [
    PaperComponent
  ]
})
export class PapaerModule { }

So far so good, no angular errors.

book.module.ts

import { NgModule } from '@angular/core';
import { BookComponent } from './book.component';
import { PaperModule } from './paper.module'

@NgModule({
  declarations: [
    BookComponent
  ],
  imports: [
    PaperModule
  ],
  exports: [
    BookComponent
  ]
})
export class BookModule { }

Here, book.component.html looks like this:

<app-paper></app-paper>

Everything is still fine, no errors. But when we want to use both (not sure we will need both, maybe we will only need paper, maybe book too):

store.module.ts

import { NgModule } from '@angular/core';
import { BookModule } from './book.module'
import { PaperModule } from './paper.module'

@NgModule({
  imports: [
    BookModule,
    PaperModule
  ]
})
export class StoreModule { }

Here's the error I get:

Error: Uncaught (in promise): Error: Type PaperComponent is part of the declarations of 2 modules: BookModule and StoreModule! Please consider moving PaperComponent to a higher module that imports BookModule and StoreModule. You can also create a new NgModule that exports and includes PaperComponent then import that NgModule in BookModule and StoreModule.

How could I structure this all the way, in order to export both component (BookComponent and PaperComponent) so I could use them in other module? I wanna make PaperComponent reusable by BookModule and Storemodule too. For some module I only need paper, but for some other I need book which includes paper as well. I hope you can understand my problem!


Solution

  • I just ran your setup through stackblitz and it is without problem.

    Check your code to make sure that BookModule does not declare PaperComponent.

    book.module.ts

    import { NgModule } from '@angular/core';
    import { BookComponent } from './book.component';
    import { PaperModule } from './paper.module';
    import { PaperComponent } from './paper.component';
    
    @NgModule({
      declarations: [
        BookComponent,
        // This would be a problem
        PaperComponent
      ],
      imports: [
        PaperModule
      ],
      exports: [
        BookComponent,
      ]
    })
    export class BookModule { }