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?
Sharing moduleslink You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your application. Notice the following: It imports the CommonModule because the module's component needs common directives.
Instead of importing these common modules and components in every feature module, you can create a shared module that has all these modules and components. Import them into a shared module and import this shared module into all feature modules. This will save imports and a lot of coding lines.
To use component from another module with Angular, we export the module from the source module. And then we import the exported module from the destination module. to export FirstPage and ImportantCopmonent by putting it in the exports array in the source module.
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 { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With