组件中的Angular 4路由组件

时间:2017-12-13 14:41:10

标签: angular angular4-router

如果路由器位于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]

1 个答案:

答案 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演示此