Angular 子路由加载父组件而不是子组件

Angular child route loading parent instead of child component

我正在尝试根据父子概念导航我的 Angular 应用程序。 加载时,加载父组件而不是子组件,但 url 似乎是

const appRoute: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent },
  {
    path: 'solutions', component: SolutionComponent,
    children: [
      { path: 'cog', component: CogComponent }
    ]
  },
  { path: 'portfolio', component: PortfolioComponent },
  { path: '**', component: PortfolioComponent }
];

当我 运行 solutions/cog 它重定向到 SolutionComponent 但它应该加载 CogComponent

编辑:1

当我使用

时它会起作用
const appRoute: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'solutions', component: SolutionComponent },
  { path: 'solutions/cog', component: CogComponent },
  { path: 'portfolio', component: PortfolioComponent },
  { path: '**', component: PortfolioComponent }
];

但我希望它应该从上面的方法加载。

请帮忙解决这个问题。

...
{
    path: 'solutions', component: SolutionComponent,
    children: [
        { path: 'cog', component: CogComponent }
    ]
},
...

由于您已经为路径 solutions 声明了 component 因此它显示 SolutionComponent 并且它将在嵌套的 router-outlet 中呈现 CogComponent

{ path: 'dashboard', component: DashboardComponent },
{
    path: 'solutions'
    children: [
        { path: 'cog', component: CogComponent },
        { path: '', component: SolutionComponent, pathMatch: 'full'}
    ]
},
...

以上路线应该如您所愿。

您的第二种方法有效,因为 Angular 将在父路由器插座本身中加载 CogComponent 模板。如果那是您想要的,那么您可以采用这种方法。

但是如果你想让 SolutionComponent 作为 CogComponent 的父级,那么你必须向 solution.component.html 添加一个 <router-outlet></router-outlet>

方法如下:

...

<router-outlet></router-outlet>

这将告诉 Angular 它需要在其中加载 CogComponent,因为 /cog/solution 路由的子路由。


这里有一个 Working Sample StackBlitz 供您参考。