如果再次导航到父路径,Angular 子组件将从路由器出口中删除

问题描述 投票:0回答:1

我有一个 Angular 组件,它根据条件通过

<router-outlet>
显示一个或另一个子组件。

当页面最初使用路径

/orders
加载时,父组件
OrderComponent
会评估其
ngOnInit()
中的条件并导航到相对的子路由。目标组件已正确渲染。

但是,通过单击指向同一父路线 (

/orders
) 的链接,
<router-outlet>
中的内容会消失,而我希望内容保持不变。当然,任何
ngOnInit()
都不会被调用,因为路径和组件相同(父级和子级不会重新加载)。我不明白是什么让孩子的内容消失了。删除选项
{ skipLocationChange: true }
也不会带来任何改进。

父模板

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

父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 });
    }
  });

}

模块路线

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),
      },
   ]
}
angular angular-routing angular-load-children
1个回答
0
投票

“我不明白是什么让孩子的内容消失了”。

只有当路由与其配置的路径匹配时,子内容才会出现。如果路径发生变化并且不再与配置的路由匹配,则不会渲染任何子组件。

这是一个 StackBlitz 演示,可能有助于说明问题。

© www.soinside.com 2019 - 2024. All rights reserved.