Angular lazy loading children modules in a parametric parent route

574 Views Asked by At

I have this correctly working example of lazy loading children from modules

{
    path: 'FIRST', children: [
      {    path: '', component: OutletComponent  },
      {
        path: '', component: OutletComponent, outlet: 'sidebar',
        loadChildren: () =>
          import('./components/.../first.module').then((m) => m.FirstModule)
      },
    ]
  },
  {
    path: 'SECOND', children: [
      {    path: '', component: OutletComponent  },
      {
        path: '', component: OutletComponent, outlet: 'sidebar',
        loadChildren: () => 
          import('./components/.../second.module').then((m) => m.SecondModule)
      },
    ]
  }

OutletComponent is just a simple complnent with this content template: <router-outlet></router-outlet>, used to display child content.

Just ignore for now the 2 nested children with empty path, required to use correctly a secondary outlet named sidebar. This example works meaning that when navigate FIRST module First is loaded and in it simple code is executed to load new route for FIRST and display FirstComponent (SecondModule is equal)

const routes: Routes = [{path: '', component: FirstComponent}];

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

Now my question is, I don't want to repeat this code for FIRST/SECOND/THIRD/.../100th and I would like to change routes with some parametric field like:

{
    path: ':id', children: [
      {path: '', component: OutletComponent },
      {
        path: '', component: ContainerComponent, outlet: 'sidebar',
        
    /** IN THIS LOAD CHILDREN BE ABLE TO LOAD DIFFERENT CHILDREN BASED on :id parent value   */
        loadChildren: () =>
          import('./..../DynamicModule').then((m) => m.DynamicModule)
      },
    ]
  }

Purpose is create a DynamicModule that can switch if :id === FIRST to load FIRSTModule or SECONDModule if === SECOND.

so far I had 2 problems

  • in this scenario with parametric parent loadChildren is called only once, DynamicModule is created once so I can't put in there a logic to load different paths each time is called
  • most important I can't detach the :id value (if is FIRST or SECOND) from this module to load different module and paths.

There is any way around this problem to adapt First solution with static definition of all routes wits some generic path: ':parameterId' ?

0

There are 0 best solutions below