我试图基于父子概念导航我的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 }
];
但是我希望它应该从上述方法加载。
请帮助解决此问题。
答案 0 :(得分:1)
...
{
path: 'solutions', component: SolutionComponent,
children: [
{ path: 'cog', component: CogComponent }
]
},
...
由于您为路径component
声明了solutions
,因此它显示了SolutionComponent
,它将在嵌套的CogComponent
中呈现router-outlet
{ path: 'dashboard', component: DashboardComponent },
{
path: 'solutions'
children: [
{ path: 'cog', component: CogComponent },
{ path: '', component: SolutionComponent, pathMatch: 'full'}
]
},
...
上述路线应能按预期工作。
答案 1 :(得分:0)
您的第二方法可以正常工作,因为Angular会将CogComponent
模板加载到父路由器出口本身中。如果那是您想要的,那么最好采用这种方法。
但是,如果您想将SolutionComponent
作为CogComponent
的父项,则必须在<router-outlet></router-outlet>
上添加solution.component.html
。
方法如下:
...
<router-outlet></router-outlet>
这将告诉Angular,由于CogComponent
是/cog
路由的子路由,因此需要在其中加载/solution
。
这是您推荐的Working Sample StackBlitz。