How to create a shared module in Angular
Creating shared modules is essential for organizing reusable components, directives, and pipes that are used across multiple feature modules in Angular applications. As the creator of CoreUI, a widely used open-source UI library, I’ve architected shared module systems in countless Angular projects over 25 years of development. From my expertise, the most effective approach is using Angular CLI to generate a shared module and then importing/exporting common components. This promotes code reusability and maintains clean module architecture.
Use Angular CLI to generate a shared module and export reusable components.
ng generate module shared
ng generate component shared/loading-spinner
Here the first command creates a new shared module with @NgModule decorator. The second generates a reusable component inside the shared module. In the shared module, import and export components that other modules will use. Import CommonModule for basic Angular directives, and export components, directives, or pipes that should be available to importing modules.
Best Practice Note:
This is the same shared module architecture we use in CoreUI Angular components for maximum reusability. Keep shared modules focused on truly reusable elements and avoid importing feature-specific dependencies to maintain loose coupling between modules.



