带孩子的Angular 2条路线

时间:2019-01-18 13:49:44

标签: angular

我正在尝试创建默认路线(家),并且我希望“家”具有子路线。因此,当您转到Home时,应加载home组件,而转到Homes子级时,应加载特定的子路由。但是现在我的home组件已加载,但我无法导航到其中的任何子组件。我在做什么错了?

这是我的核心路线:

export const coreRoutes: Routes = [
  { 
    path: '', 
    redirectTo: 'home', 
    pathMatch: 'full' 
  },
  { 
    path: 'home', 
    component: HomeComponent, 
    data: { breadcrumb: 'Home', icon: 'fa-home' }, 
    children: homeChildRoutes 
  }
];

这是我的homeChildRoutes:

export const homeChildRoutes: Routes = [
  { 
    path: '', 
    redirectTo: 'home', 
    pathMatch: 'full' 
  },
  { 
    path: 'first-child', 
    component: firstChildComponent, 
    data: { breadcrumb: 'First Child', parent: 'home' } 
  },
  { 
    path: 'second-child', 
    component: secondChildComponent, 
    data: { breadcrumb: 'Second Child', parent: 'home'  } 
  }
];

2 个答案:

答案 0 :(得分:1)

/home页上,将显示HomeComponent

/home/first-child页上,显示firstChildComponent,而HomeComponent隐藏了

// core routes
export const coreRoutes: Routes = [
  { 
    path: 'home', 
    children: homeChildRoutes
  },
  { 
    path: '', 
    redirectTo: 'home', 
    pathMatch: 'full' 
  },
];

// child routes
export const homeChildRoutes: Routes = [
  {
    path: '',
    component: HomeComponent,
    data: { breadcrumb: 'Home', icon: 'fa-home' },
  },
  { 
    path: 'first-child', 
    component: firstChildComponent, 
    data: { breadcrumb: 'First Child', parent: 'home' } 
  },
  { 
    path: 'second-child', 
    component: secondChildComponent, 
    data: { breadcrumb: 'Second Child', parent: 'home'  } 
  },
];

答案 1 :(得分:1)

路线可以简化为此:

export const coreRoutes: Routes = [
  { 
    path: 'home', 
    component: HomeComponent, 
    data: { breadcrumb: 'Home', icon: 'fa-home' }, 
    children: [
      { 
         path: '', 
         redirectTo: 'home', 
         pathMatch: 'full' 
      },
      { 
        path: 'first-child', 
        component: firstChildComponent, 
        data: { breadcrumb: 'First Child', parent: 'home' } 
      },
      { 
        path: 'second-child', 
        component: secondChildComponent, 
        data: { breadcrumb: 'Second Child', parent: 'home'  } 
      }
    ] 
  },
  ,
 { 
    path: '', 
    redirectTo: 'home', 
    pathMatch: 'full' 
 }
];

确保您的HomeComponent具有路由器出口。否则您的子组件将不可见。

请参考this以获取代码。