Search code examples
angulartypescriptshared-module

Shared Module exports


I have certain components in a module named 'button module' that I would like to use in my own custom module named 'products module'. The component in buttons module is a 'dropdown-buttons' component. I know that I have to create a shared module file and then export these components in that module. But I am a little bit confused as I do not know if I create a shared module then do I need to still add these components in the declaration of both modules i.e, buttons and products module? What would be the perfect way to model shared module file? here is my code

buttons.module.ts

const components = [
  ButtonsComponent,
  DefaultButtonsComponent,
  HeroButtonComponent,
  ShapeButtonsComponent,
  SizeButtonsComponent,
  ActionGroupsComponent,
  DropdownButtonsComponent,
  BlockLevelButtonsComponent,
  ButtonGroupsComponent,
  IconButtonsComponent,
  LabeledActionsGroupComponent,
];

@NgModule({
  imports: [
    ThemeModule
  ],
  exports: [
    ...components,
  ],
  declarations: [
    ...components,
  ],
  providers: [],
})
export class ButtonsModule { }

products.module.ts

@NgModule({
    imports: [ 
        ThemeModule,
        NbCardModule,
        FormsModule,
        ProductsRoutingModule,
        // DropdownButtonsComponent,
    ],
    declarations: [
        ProductsComponent,
        AllproductsComponent,
        AddproductComponent,
    ]
})

export class ProductsModule { }

Solution

  • No you can't add any component to the declaration list in two module this will throw an error , you can create a module just for this component and imported in the other modules.

    @NgModule({
    
      exports: [
        DropdownButtonsComponent,
      ],
      declarations: [
        DropdownButtonsComponent,
      ],
      providers: [],
    })
    
    export class DropdownButtonsModule { 
    }
    

    ButtonsModule

    @NgModule({
      imports: [
        ThemeModule,
        DropdownButtonsModule 
      ],
      exports: [
        ...components,
      ],
      declarations: [
        ...components,
      ],
      providers: [],
    })
    export class ButtonsModule { }
    

    ProductsModule

    @NgModule({
        imports: [ 
            ThemeModule,
            NbCardModule,
            FormsModule,
            ProductsRoutingModule,
            DropdownButtonsModule ,
        ],
        declarations: [
            ProductsComponent,
            AllproductsComponent,
            AddproductComponent,
        ]
    })
    
    export class ProductsModule { }