【问题标题】:Angular 2 routes with children带孩子的 Angular 2 路线
【发布时间】:2019-01-18 13:49:43
【问题描述】:

我正在尝试创建一个默认路由(家),我希望“家”有子路由。这样当你去 Home 时,应该加载 homecomponent,而当你去 Homes children 时,应该加载特定的 childroute。但现在我的家庭组件加载,但我无法导航到它的任何孩子。我做错了什么?

这是我的核心路线:

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'  } 
  }
];

【问题讨论】:

  • 你想在同一个路由器插座中渲染 HomeComponent 和 childComponents 吗?重要的是要了解子路由在父组件的路由器出口中呈现子组件的内容。你想达到什么目的?
  • 我想是的,我对 Angular 还是很陌生,但我想要实现的是在导航到根目录时显示 homecomponent 并显示一些内容。然后当你导航到它的孩子时,孩子的内容应该是可见的。

标签: angular


【解决方案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'  } 
  },
];

【讨论】:

  • 对不起,回答晚了,这行得通,但我看不出我哪里做错了?
  • 我认为您看不到子组件,因为 HomeComponent 中没有 。 Manu Bhardwaj 的回答也是正确的,但取决于您喜欢哪种行为:我的 home、child1 或 child2 一个一个显示,或者 Manu Bhardwaj,其中 child1 或 child2 在 HomeComponent 中可见
【解决方案2】:

路线可以简化为:

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 获取代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2017-08-26
    • 2017-06-15
    • 2017-07-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    相关资源
    最近更新 更多