How to use components from modules in others lazy load modules

Issue

I am trying to use some components from a specific module inside of others components from lazy load modules.

I gonna show you example for better understanding!

project:
app.module
app.route
shared.module

modules/
    lazy-load-1.module
    lazy-load-2.module
    reusable.module

inside of each module I have imported a shared.module.
inside of reusable.module, I have some components to be used inside of others module, but that others module are lazy load modules.

ex:

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

@NgModule({
  imports:      [ SharedModule, ReusableModule ],
  declarations: [ someImportsHere ],
  bootstrap: [AppComponent],
})
export class AppModule { }

const appRoutes: Routes = [
  {
    path: 'lazy-load-1',
    loadChildren: 'app/modules/lazy-load-1/lazy-load-1.module#LazyLoad1Module',
  },
  {
    path: 'lazy-load-2',
    loadChildren: 'app/modules/lazy-load-2/lazy-load-2.module#LazyLoad2Module',
  },
  {
    path: '**',
    redirectTo: 'lazy-load-1'
  }
];


@NgModule({
   exports: [
      RouterModule
   ],
   imports: [
      RouterModule.forRoot(appRoutes, { useHash: true })
   ]
})

export class AppRouter { }

modules/

@NgModule({
  imports:      [ SharedModule ],
  declarations: [ TestComponent ],
})
export class LazyLoad1Module { }

@NgModule({
  imports:      [ SharedModule ],
  declarations: [ OtherTestComponent ],
})
export class LazyLoad2Module { }

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

I am trying something like this above, but when I try to use a ReusableComponent inside of LazyLoad modules I got this error:
rejection: Error: Template parse errors:
‘app-reusable-component’ is not a known element.

Solution

if you have multiple modules and want to share your component to other modules you need to export it

like this

@NgModule({
  declarations: [your_component],
  exports: [your_component]
})

Answered By – John Velasquez

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.