Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a lazy loaded module inherit App Modules Declarations?

Tags:

angular

I have a lazy loaded module that needs to use a component. I have added it to app modules declarations and expect that this should make the declared component app wide.

Although Angular can't recognize the component in the lazy loaded module. I tried adding it to both module declarations then and got a warning asking to add the declaration in a higher module above the app.module and lazyLoaded.module.

e.g. (nameOfModule/Component)

Error: Type (DeclareMeComponent) is part of the declarations of 2 modules: (AppModule) and (LazyLoadedModule)! Please consider moving (DeclareMeComponent) to a higher module that imports AppModule and (LazyLoadedModule). You can also create a new NgModule that exports and includes (DeclareMeComponent) then import that NgModule in (AppModule) and (DeclareMeComponent).

What is higher than app.module? and how can I get the lazy loaded module to inherit/use the declared component along with app module?

like image 772
Jonathan002 Avatar asked Aug 08 '17 06:08

Jonathan002


1 Answers

Higher than AppModule would be a SharedModule. Here you can define components which you will use in your AppModule and inside any lazy loaded modules.

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    DeclareMeComponent
  ],
  exports: [
    DeclareMeComponent,
    CommonModule
  ]    
})
export class SharedModule {}

Here you will declare and export components, directives, pipes, the whole shebang. Core building blocks which you will use throughout your entire application. Here you will probably also import and export the CommonModule. It's like the BrowserModule, but then something you can import more than once inside an application.

You can now use your shared component inside your AppModule and any other module by importing it.

@NgModule({
  imports: [
    BrowserModule,
    SharedModule
  ]   
})
export class AppModule {}

As you can see, there is no need to declare DeclareMeComponent inside the AppModule, because it's imported from the higher SharedModule

like image 111
Poul Kruijt Avatar answered Sep 29 '22 15:09

Poul Kruijt