【问题标题】:Angular 4 routing component in component组件中的Angular 4路由组件
【发布时间】:2017-12-13 14:41:10
【问题描述】:

如果路由器位于/client/product 相同,我有一个正在加载的DashboardComponent

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 也是如此

【问题讨论】:

    标签: angular angular4-router


    【解决方案1】:

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

    // 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 被加载到子路由器出口(@98​​7654328@ 内部)。这是一个stackblitz 演示这个

    【讨论】:

    • @MeesKluivers 作为旁注,我将在DashboardComponent children: [{path: '', pathMatch: 'full', redirectTo: 'client'}] 下添加另一个路由定义,因此当用户仅点击/dashboard 时,它们将被重定向到/dashboard/client。我已经更新了我的 stackblitz
    • 啊,我明白了,我所做的是添加路径:'',然后加载 ClientComponent。谢谢!
    猜你喜欢
    • 2017-11-21
    • 2018-03-08
    • 2019-01-14
    • 1970-01-01
    • 2018-04-24
    • 2018-02-08
    • 1970-01-01
    • 2016-12-19
    • 2017-10-05
    相关资源
    最近更新 更多