Many Modules using the same component causes error - Angular 2

BeniaminoBaggins picture BeniaminoBaggins · Oct 8, 2016 · Viewed 24.7k times · Source

I have a shared component called GoComponent that I want to use in 2 modules: FindPageModule and AddPageModule.

When I add it in the declarations of "FindPageModule" and in my "AddPageModule" I get an error:

find:21 Error: (SystemJS) Type GoComponent is part of the declarations of 2 modules: FindPageModule and AddPageModule! Please consider moving GoComponent to a higher module that imports FindPageModule and AddPageModule. You can also create a new NgModule that exports and includes GoComponent then import that NgModule in FindPageModule and AddPageModule.

So I take it out of them both and add it in AppModule declarations, which does import FindPageModule and AddPageModule, and I get an error in a component called "FindFormComponent" which is in the declarations of FindPageModule and uses "GoComponent":

zone.js:355 Unhandled Promise rejection: Template parse errors:
'go' is not a known element:
1. If 'go' is an Angular component, then verify that it is part of this module.
2. If 'go' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. (" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                [ERROR ->]<go></go>
            </div>
        </div>
"): FindFormComponent@101:4 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors:
'go' is not a known element:
1. If 'go' is an Angular component, then verify that it is part of this module.
2. If 'go' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. (" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                [ERROR ->]<go></go>
            </div>
        </div>
"): FindFormComponent@101:4

How do I let components such as FindFormComponent that are declared in FindPageModule use GoComponent and also let components declared by AddPageModule use GoComponent?

Answer

Paul Samsotha picture Paul Samsotha · Oct 8, 2016

Yes, components can be declared only in one module, and nor are their access inherited in any way, meaning declaring it in the main app module will not give you access to it in any other module.

If you have a component that is used by other modules, generally they way to go is to put it in a shared module

Include component in a shared module:

@NgModule({
  declarations: [ SharedComponent ],
  exports: [ SharedComponent ]
})
export class SharedModule {}

How to use the shared module elsewhere:

@NgModule({
  imports: [ SharedModule ]
})
class ModuleWithComponentThatUsesSharedComponent {}

See Also