How to share components between modules in Angular 2?

user1620696 picture user1620696 · Jan 9, 2017 · Viewed 16.7k times · Source

I'm in doubt in how to share components between modules in Angular 2. The point is: I have two modules in the app, the 'Customers Module' and the 'Suppliers Module'.

Both these modules, in their components, make use of the AddressComponent and the EmailComponent. They also both make use of the interfaces Address and Email.

Now, currently I have lots of duplication, because I've copied and pasted these components and interfaces on both modules. This is obviously just plain wrong.

I need a way to import those components to be used on both modules. But I have no idea on how to do it.

Should I create another module for this shared stuff and import it in both? What is the right way to share components between modules in Angular 2?

Answer

Pankaj Parkar picture Pankaj Parkar · Jan 9, 2017

Create a shared NgModule that will have all common Component/Service/Pipe. By doing so you will avoid code duplication. It will make code modularize, plug-able & testable.

In order to use AddressComponent & EmailComponent in other modules, you need to export them from the shared module:

Code

@NgModule({
   imports: [CommonModule],
   declarations: [AddressComponent, EmailComponent],
   providers: [MySharedService],
   exports: [AddressComponent, EmailComponent],
})
export class SharedModule { }

While Consuming SharedModule, all you have to do is import SharedModule

@NgModule({
   imports: [CommonModule, SharedModule, ... ],
   providers: [..]
})
export class CustomersModule { }