Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share components between modules in Angular 2?

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?

like image 868
user1620696 Avatar asked Jan 09 '17 03:01

user1620696


People also ask

How do I share a component between modules?

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.

How can I use a module present in shared module in module?

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.

Can we import a component from another module in Angular?

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.


1 Answers

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 { }
like image 161
Pankaj Parkar Avatar answered Sep 28 '22 10:09

Pankaj Parkar