angularangular-routingangular-lazyloading

Angular lazy load with named outlet not working


I created a products folder which contains products-home.component(parent) and products-list.component(child) with named outlet.

I get Error: Cannot match any routes. URL Segment: 'products' when navigated to products-list using lazy load.

This is working when it is eagerly loaded

app.module.ts

@NgModule({
  imports:      [ ...,ProductsModule ]
})

products.module.ts

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: "products",
        component: ProductsHomeComponent,
        children: [
          {
            path: "products-list",
            component: ProductsComponent,
            outlet: "content"
          }
        ]
      }
    ])
  ]
})

This is not working when it is lazy loaded

app.module.ts

const LazyRoutes: Routes = [
  {
    path: 'products',
    loadChildren: './products/products.module#ProductsModule'
  }
];
@NgModule({
  imports:      [ RouterModule.forRoot(LazyRoutes) ]
})

products.module.ts

@NgModule({
  imports: [
    RouterModule.forChild([
      {
        path: "",
        component: ProductsHomeComponent,
        children: [
          {
            path: "products-list",
            component: ProductsComponent,
            outlet: "content"
          }
        ]
      }
    ])
  ]
})

Stackblitz


Solution

  • This is a known issue in angular - 22346 and 10981

    When module is lazy load then parent component's path needs to be set as empty. This is the issue here, the child component with named outlet only works when parent has a path(non-empty).

    I got this working by adding fake path.

    {
        path: "home", <--Here
        component: ProductsHomeComponent,
        children: [
          {
            path: "products-list",
            component: ProductsComponent,
            outlet: "content"
          }
        ]
    }
    

    Since the route config is changed, we have to change routerLink as 'products/home'

    <a [routerLink]="['/products/home', { outlets: { 'content': ['products-list'] } }]">Navigate to Products(Products List)</a>