Angular 组件中有4个路由组件

Angular 4 routing component in component

如果路由器位于 /client,我有一个正在加载的 DashboardComponent/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 它在 DashboardComponent 中加载 ClientComponent 并且 ProductComponent

也是如此

您可以使用子路由器插座完成此操作

// 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 被加载到子路由器出口(在 DashboardComponent).这是一个 stackblitz 演示