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

Angular5中router-outlet无法嵌入组件问题求助

我之前刚学Angular的时候也踩过这个坑!核心问题是你的路由没把Sample组件设为Home的子路由,再加上routerLink路径没对应上,导致点击后直接替换了整个页面的路由,而不是嵌套在Home的router-outlet里。下面一步步帮你解决:

第一步:修正路由配置(routes.ts)

你现在的路由应该是把sample设成了顶级路由,这样它会直接替换App组件里的router-outlet,而不是Home组件里的。改成子路由配置就对了:

import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { SampleComponent } from './sample/sample.component';

const routes: Routes = [
  // 将Sample作为Home的子路由
  {
    path: 'home',
    component: HomeComponent,
    children: [
      { path: 'sample', component: SampleComponent },
      // 可选:如果访问/home时想默认显示某个组件,可以加这个
      // { path: '', component: DefaultHomeContentComponent }
    ]
  },
  // 默认重定向到home页面
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

export const routing = RouterModule.forRoot(routes);

第二步:修正Home组件里的routerLink路径

你现在用的/sample是绝对路径,指向顶级路由。改成相对路径(或者完整的子路由路径):
把桌面端菜单里的代码:

<li><a routerLink="/sample" routerLinkActive='active'>Sample 1</a></li>

改成:

<li><a routerLink="sample" routerLinkActive='active'>Sample 1</a></li>

或者用绝对路径写法:

<li><a routerLink="/home/sample" routerLinkActive='active'>Sample 1</a></li>

另外,移动端菜单里的Sample 1还是普通的href="#",也要改成routerLink才能生效:

<li><a routerLink="sample" routerLinkActive='active'>Sample 1</a></li>

第三步:确认AppComponent有顶级router-outlet

你的AppComponent模板里必须有一个<router-outlet></router-outlet>,这样HomeComponent才能被加载到这里,然后HomeComponent里的router-outlet再加载Sample组件。比如AppComponent的html应该是:

<!-- app.component.html -->
<router-outlet></router-outlet>

这样调整后,点击Sample 1链接时,Sample组件就会乖乖嵌入到Home页面的router-outlet位置,不会再跳转到单独页面了~

内容的提问来源于stack exchange,提问作者stack questions

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:46:18