Angular 6/7/8嵌套子路由用loadChildren不显示问题求助
我仔细看了你的代码,发现几个关键问题导致点击带routerLink的列表项时,无法正确加载EditDetailsComponent,下面给你逐一排查并解决:
1. 路由配置冲突:同时使用component和loadChildren
在app-routing.module.ts的子路由配置中,你同时指定了component: RightPanelComponent和loadChildren,这两个配置是互斥的——懒加载模块(loadChildren)会接管该路径下的所有路由规则,直接指定component会覆盖懒加载模块的路由逻辑,导致RightPanelModule里的子路由(editDetails/:id)无法生效。
修改app-routing.module.ts
移除子路由中的component配置,只保留懒加载规则:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {PatientsDataComponent} from './main-page/main/patients/patients-data/patients-data.component'; const routes: Routes = [{ path: 'patients', component: PatientsDataComponent, children: [{ path: '', loadChildren: () => import('./main-page/main/patients/right-panel/right-panel.module').then(m => m.RightPanelModule), data: { preload: true } }] }]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
2. 确认RouterLink路径的正确性
你的列表项中routerLink使用的是['editDetails', pat.patient_id],需要确保这个相对路径是基于当前路由上下文的。由于PatientsDataComponent对应/patients路径,而EditDetailsComponent的路由是/patients/editDetails/:id,这个相对路径是正确的,但如果你的模板所在组件的路由上下文不同,也可能导致跳转失败。
可以尝试使用绝对路径来验证:
[routerLink]="['/patients/editDetails', pat.patient_id]"
3. 确保层级路由的<router-outlet>存在
- 确认
PatientsDataComponent的模板中包含<router-outlet>,用于加载RightPanelComponent - 确认
RightPanelComponent的模板中包含<router-outlet>,用于加载EditDetailsComponent
你提到已经在RightPanelComponent中添加了<router-outlet>,只要PatientsDataComponent也有对应的<router-outlet>,层级路由就能正常渲染。
4. 验证懒加载模块的导入
你的RightPanelModule已经正确导入了RightPanelRoutingModule,并且声明了EditDetailsComponent,这部分配置是没问题的,不需要修改。
完成以上修改后,点击列表项应该就能正确跳转到EditDetailsComponent,同时保留父组件的视图了。
内容的提问来源于stack exchange,提问作者Judah Irani

