Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 RC5 shared Component between Modules

Tags:

angular

I'm just updating my angular2-app to new RC5. I got quite far, and everything seems ok, but now I want to re-organize it into NgModules and came across one thing: I used a component ("ComponentA") across multiple other components in different Modules (say ModuleA & ModuleB).

As soon as use it that way, I get an:

Uncaught Type ComponentA is part of the declarations of 2 modules: ModuleA and ModuleB!

Error.

As far as I see, the only way to get around that is to use a Shared-Module with all my common stuff, is that right? Or is there an easier way to share components across Modules?

Thanks in advance :)

like image 536
Mr. Muh Avatar asked Aug 10 '16 16:08

Mr. Muh


2 Answers

You have to make a module for the shared component and import this module where you want to use this component.

As the error messages says a component (or directive, or pipe) can only be listed in directives of exactly one module.

If you want to reuse, then you need to add the module that contains it to @NgModule({imports: [...]}) of the module where you want to use it.

like image 173
Günter Zöchbauer Avatar answered Oct 06 '22 07:10

Günter Zöchbauer


I make a module that contains ALL my shared components.

This makes it much easier to import it in my other modules.

Pro tip: put routing into your modules, and try - just for fun - to make one of them lazy loaded.

Then you'll think: "whoaaaaa modules are cooooolllll"

like image 34
Spock Avatar answered Oct 06 '22 09:10

Spock