Search code examples
angularangular-ui-routerangular4-router

Issue on angular nested lazy routing


i m trying to implement nested child lazy load routing but i got some problem regarding routing.

here is my routing code:- app.modules.ts looks like

  RouterModule.forRoot([
                         {path:'',redirectTo:'home',pathMatch:'full'},
                         {path:'home',component:HomeComponent},
          {path:'pages',loadChildren:'./pages/pages.module#PagesModule' },
          {path:'**',component: NotFoundComponent}
                       ],{enableTracing:true}) 

pages.module.ts looks like:-

         RouterModule.forChild([
             { path:'', component:PagesComponent,
               children:[
                         {path:'',redirectTo:'user',pathMatch:'full'},
                         {path:'user',component:UserComponent },                                   


    {path:'forms',loadChildren:'./forms/forms.module#CustomFormsModule'}]
      }

]) 

forms.modules.ts:-

RouterModule.forChild([
    {path:'',component:FormsComponent,
          children:[
            {path:'',redirectTo:'general',pathMatch:'full'},
            {path:'general',component:GeneralComponent},
            {path:'advance',component:AdvanceComponent}
        ] }
])

when I type path http://localhost:4200/pages - it redirects me to /pages/general and even if i type pages/general it give me general component as there is no sure route defined in my routermodule.


Solution

  • The problem is that you are importing Lazy-loaded modules in your code

    //pages.module.ts
    import { CustomFormsModule } from './forms/forms.module';
    //...
      imports: [
    CommonModule,
    CustomFormsModule, //<--Don't do that
    

    When using lazy loaded modules, do not import them explicitely, otherwise the router gets confused

    Here is the edited stackblitz https://stackblitz.com/edit/angular-nested-lazy-route-kahove