You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15子路由为何加载至父router-outlet?如何修正?

解决Angular子路由加载到主路由出口的问题

你当前的路由配置中,person/:id与person的空路径路由是同级关系,这导致访问person/6时,Angular会替换主路由出口的内容,而非加载到PersonMainComponent内部的子路由出口。只需调整路由嵌套结构并修正路由链接即可解决:

1. 调整Person路由配置

将:id路由嵌套到PersonMainComponent对应的路由的children数组中,使其成为PersonMainComponent的子路由:

{
  path: 'person',
  children: [ 
    {
      path: '',
      component: PersonMainComponent,
      // 新增子路由配置,将:id路由归属到PersonMainComponent下
      children: [
        {path: ':id', component: PersonFieldDetailsComponent}  
      ]
    }
  ]
}

2. 修正PersonMainComponent的路由链接

由于:id现在是PersonMainComponent的子路由,使用相对路径导航确保路由指向正确:

<a routerLink="./6">Should Load Into Child Outlet</a> 
Child Outlet: <router-outlet></router-outlet>

修改完成后,点击链接时,主路由出口会保持加载PersonMainComponent,其内部的子路由出口则会加载PersonFieldDetailsComponent,符合你的预期。

内容的提问来源于stack exchange,提问作者TimTheEnchanter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:05:17