Angular子组件加载异常:点击按钮未在新页面加载而显示于父组件下方
Angular路由问题:组件未在新页面加载而是显示在父组件下方
期望点击按钮后,ApplicationModuleComponent组件在新页面中加载,但实际点击后该组件却显示在父组件下方。
相关代码与结构
路由配置(app-routing.module.ts)
const routes: Routes = [ { path: '', component: SideNavbarComponent }, { path: 'application', component: ApplicationModuleComponent, children:[ { path: 'sgldn', component : SgldnEntityComponent, children:[ { path:'trademon', component:TradeMonitoringComponent }, { path:'eod', component:EodMonitoringComponent } ] }, { path:'sgparis', component : SgpmEntityComponent } ] } ];
SideNavbarComponent模板(side-navbar.component.html)
<p>side-navbar works!</p> <app-home></app-home>
HomeComponent模板(home.component.html)
<p>home works!</p> <button routerLink="/application">APPLICATION</button> <router-outlet></router-outlet>
ApplicationModuleComponent模板(application-module.component.html)
<p>application-module works!</p>
问题原因
当前路由结构与router-outlet的位置不匹配:
- 根路由
''直接绑定SideNavbarComponent,但该组件没有根级别的<router-outlet>; HomeComponent中的<router-outlet>是嵌套路由出口,而/application是根级别路由,却被错误渲染到了这个嵌套出口中,导致组件显示在父组件下方。
解决方案
1. 调整路由结构,将SideNavbarComponent设为布局父组件
修改app-routing.module.ts,让SideNavbarComponent作为根布局,包含首页子路由:
const routes: Routes = [ { path: '', component: SideNavbarComponent, children: [ { path: '', component: HomeComponent } // 首页作为子路由加载 ] }, { path: 'application', component: ApplicationModuleComponent, children:[ { path: 'sgldn', component : SgldnEntityComponent, children:[ { path:'trademon', component:TradeMonitoringComponent }, { path:'eod', component:EodMonitoringComponent } ] }, { path:'sgparis', component : SgpmEntityComponent } ] } ];
2. 给SideNavbarComponent添加根路由出口
修改side-navbar.component.html,移除直接引入的<app-home>,替换为根级别<router-outlet>:
<p>side-navbar works!</p> <router-outlet></router-outlet>
3. 移除HomeComponent中的嵌套路由出口
HomeComponent作为首页子组件,不需要嵌套出口,修改home.component.html:
<p>home works!</p> <button routerLink="/application">APPLICATION</button>
调整完成后,点击按钮跳转到/application时,Angular会替换根路由出口的内容,ApplicationModuleComponent将在新的页面布局中加载。
内容的提问来源于stack exchange,提问作者Anurag Tripathy
相关产品推荐
相关产品推荐

