如果路由器位于DashboardComponent
且/client
位置相同,则会加载/product
:
export const routes: Routes =
[
{ path: '', component: HomeComponent },
{ path: 'client', component: DashboardComponent },
{ path: 'product', component: DashboardComponent }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class RoutesModule { }
然后我像这样加载不同的组件(在dashboard.component.ts
中):
this.router.events.subscribe(path => {
if (this.router.url == "/client") {
this.isClient = true;
}
if (this.router.url != "/client") {
this.isClient = false;
}
if (this.router.url == "/product") {
this.isProduct = true;
}
if (this.router.url != "/product") {
this.isProduct = false;
}
});
然后在dashboard.component.html
我做:
<app-client *ngIf="isClient"></app-client>
<app-product *ngIf="isProduct"></app-product>
我觉得这不是这样做的方法,但是我找不到一个很好的解释如何实现这个,如果你去/dashboard/client
ClientComponent
加载DashboardComponent
内部ProductComponent
和[1:n]
答案 0 :(得分:2)
您可以使用子路由器
完成此操作// routing.module.ts
export const routes: Routes = [
{ path: '', component: HomeComponent },
{
path: 'dashboard',
component: DashboardComponent,
children: [
{
path: 'client',
component: ClientComponent
},
{
path: 'product',
component: ProductComponent
}
]
}
]
并将子路由器插座添加到DashboardComponent
<div>
dashboard component
<router-outlet></router-outlet>
</div>
因此,当用户转到/dashboard/client
时,DashboardComponent
将加载到顶级路由器插座中,ClientComponent
将加载到子路由器插座中({{1} }})。这是一个stackblitz演示此