首页 文章

具有嵌套组件的Angular 5路由

提问于
浏览
0

好吧为了简单起见,我假设我有3个组件:父组件和另外两个组件(子A和子B) .

我希望父组件为 have an url prefix of '/parent' and contain one of the two other components ,默认为组件A,否则为B,他们分别拥有自己的url前缀 'childA' and 'childB' . 此外,我不希望父组件本身可见,它必须具有childA或childB可查看和 if '/parent' is called it will automatically re-route to '/parent/childA'.

到目前为止,这是我在我的路由器中,它没有工作我在路由到'/ parent'时在控制台上收到无效路径错误,当我路由到'/ parent / child [AorB]时我的浏览器滞后永远,永远不会路线:

{
  path: 'parent', component: ParentComponent,
  children : [
    {
      path: '',
      redirectTo: 'childA' 
    },
    {
      path: 'childA',
          component: ChildAComponent
    }, {
      path: 'childB',
      component: childBComponent
    }
  ]
}

parent的模板只是一个路由器插座,如下所示:

<router-outlet></router-outlet>

2 回答

  • 0

    需要像这样添加 pathMatch: 'full'

    {
      path: 'parent', component: ParentComponent,
      children : [
        {
          path: '',
          redirectTo: 'childA',
          pathMatch: 'full' //<--------- Need this here
        },
        {
          path: 'childA',
              component: ChildAComponent
        }, {
          path: 'childB',
          component: childBComponent
        }
      ]
    }
    
  • 0

    确保你的html中定义了2 router-outlet ,因此angular会知道哪个是父,哪个是孩子..

    您的链接代码如何?对于孩子,请使用'./',如下所示:

    [routerLink]="['./childA']"
    

    对于父母,你可以直接去......

    [routerLink]="['parent']"
    

相关问题