angularangular-materialangular-routingangular-lazyloading

Angular Material with Lazy Loading Module


i already found that which looks similar but does not help me. Lazy loading Angular modules with latest Angular material design gives error

My problem is, that i have lazy loading modules. app-routing.module.ts

const routes: Routes = [
  {path: '', redirectTo: '/home', pathMatch: 'full'},
  {path: 'home', loadChildren: () => import('./home/home-routing.module').then(m => m.HomeRoutingModule)},
  {path: '**', loadChildren: () => import('./error/error-routing.module').then(m => m.ErrorRoutingModule)}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

And home routing module looks like:

@NgModule({
  imports: [RouterModule.forChild(
    [
      {path: '', component: NavigationComponent},
    ]
  )]
})
export class HomeRoutingModule {
}

The navigation component is just the generated material schema for the sidenav. https://material.angular.io/guide/schematics#navigation-schematic

But as a result i get:

Error: src/app/home/navigation/navigation.component.html:1:1 - error NG8001: 'mat-sidenav-container' is not a known element:

  1. If 'mat-sidenav-container' is an Angular component, then verify that it is part of this module.
  2. If 'mat-sidenav-container' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Moving the sidenav code, to app.component.html everything works fine.

My home module is like

@NgModule({
  declarations: [NavigationComponent],
  imports: [
    CommonModule,
    HomeRoutingModule,
    LayoutModule,
    MatToolbarModule,
    MatButtonModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule
  ]
})
export class HomeModule { }

Have no glue what i am doing wrong?

Thx


Solution

  • To import lazy loading Module, you need to import the main module, that contain the component declarations, and the needed module for these component:

    In your app-routing.module

    //home.module and HomeModule, instead of HomeRoutingModule
    {path: 'home', loadChildren: () => import('./home/home.module').then(m => 
    m.HomeModule)}
    

    In your homeRoutingModule, you need to export RouterModule:

     @NgModule({
     imports: [RouterModule.forChild(
       [
         {path: '', component: NavigationComponent},
       ]
     )],
     exports: [RouterModule]
     })
    

    Finally, in your HomeModule, you import your HomeRoutingModule:

    imports: [
     ...
     HomeRoutingModule,
     ....
    
    ]