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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:37:26