角度子管线加载父元件而不是子元件



我正在尝试基于父子概念导航我的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'}
]
},
...

上述路线应按您的意愿运行。

您的第二个Appraoch之所以有效,是因为Angular将在父路由器出口中加载CogComponent模板。如果这是你想要的,那么你可以采用这种方法。

但是,如果要将SolutionComponent作为CogComponent的父级,则必须向solution.component.html添加一个<router-outlet></router-outlet>

方法如下:

...
<router-outlet></router-outlet>

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


这是工作样品StackBlitz供您参考。

最新更新