Search code examples
angularangular-routingangular-load-children

Angular child component removed from router-outlet if navigating again to parent path


I have an Angular component that displays one or another child component through a <router-outlet> according to a condition.

When initially the page loads with the path /orders, the parent component OrderComponent evaluates the condition in its ngOnInit() and navigates to the relative child route. The target component is rendered correctly.

However, by clicking on a link that points to the same parent route (/orders) the content in the <router-outlet> disappears, while I would expect that the content would remain intact. Of course, any of the ngOnInit() is not called, as the path is the same and the component (parent and child is not reloaded). I do not understand though what makes the child's content disappear. Removing the option { skipLocationChange: true } also does not bring any improvement.

Parent template

<h1> content </h1>
<router-outlet></router-outlet>

Parent ngOnit

ngOnInit() {
  this.orderService.isOrderEligible()
  .pipe(take(1))
  .subscribe((isOrderEligible: boolean) => {
    // According to the condition the target child route/component is loaded
    if (!isOrderEligible) {
      this.route.navigate(['orders/public-products'], { skipLocationChange: true } );
    } else {
      this.route.navigate(['orders/store-products'], { skipLocationChange: true });
    }
  });

}

Module Routes

const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,
    children: [
      {
        path: 'public-products',
        loadChildren: () => import('../orders/public-orders.module').then((m) => m.PublicOrderModule),
      },
      {
        path: 'store-products',
        loadChildren: () => import('../orders/store-orders.module').then((m) => m.StoreOrderModule),
      },
   ]
}

Solution

  • "I do not understand though what makes the child's content disappear".

    The child content will only appear when the route matches its configured path. If the path changes and no longer matches a configured route, then no child component will be rendered.

    Here is a StackBlitz demo that might help illustrate the issue.