Angular 15嵌套懒加载子路由异常:加载父组件而非子组件问题
问题原因与解决方案
核心问题:父组件缺少 <router-outlet>
你的嵌套子路由不生效的根本原因是:GamesComponent 作为父路由组件,模板里没有添加 <router-outlet> 标签。
Angular的子路由组件必须通过父组件内的 <router-outlet> 才能渲染。当你访问 /dashboard/games/game/123 时,Angular已经匹配到games路由并加载了GamesComponent,但因为没有渲染出口,子路由的GameComponent无处挂载,页面自然只会显示GamesComponent的内容。
而把game/:id移到和games同级时,它变成了dashboard的子路由,会渲染在UserDashboardComponent的<router-outlet>里,所以能正常工作。
修复步骤
- 打开
GamesComponent的模板文件(如games.component.html) - 添加
<router-outlet>标签,位置根据布局需求放置,示例:
<!-- GamesComponent 原有内容 --> <h2>游戏列表</h2> <!-- 子路由组件将在此渲染 --> <router-outlet></router-outlet>
- 保持原有路由配置不变即可:
const routes: Routes = [{ path: 'dashboard', loadComponent: () => import('./app/user-dashboard/user-dashboard.component').then((m) => m.UserDashboardComponent), canActivate: [AuthGuard], children: [ { path: '', redirectTo: 'games', pathMatch: 'full' }, { path: 'games', loadComponent: () => import('./app/user-dashboard/games/games.component').then((m) => m.GamesComponent), children: [ { path: 'game/:id', loadComponent: () => import('./app/user-dashboard/games/game/game.component').then((m) => m.GameComponent) } ] } ] }]; bootstrapApplication(AppComponent, { providers: [ importProvidersFrom(RouterModule.forRoot(routes, { enableTracing: true })) ] })
补充说明
- 独立组件模式下,路由逻辑和传统模块模式完全一致,子路由依然依赖父组件的
<router-outlet> - 开启
enableTracing: true可在控制台查看路由匹配全过程,能看到Angular确实匹配到了子路由,但因无出口无法渲染组件
内容的提问来源于stack exchange,提问作者GlennMoseley
相关产品推荐
相关产品推荐

