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
相关产品推荐
相关产品推荐

