Angular 2 Child Route

时间:2017-07-31 09:09:08

标签: angular angular-routing

我已按照以下方式配置了我的路由:

const routes: Routes = [
         { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
         { path: 'dashboard', component: HomeComponent },
         {
           path: 'contact', component: ContactComponent,
           children: [     
             {
               path: '',
               component: ContactComponent
             }, 
             {
               path: 'list',
               component: ContactlistComponent
             },      
           ]

         },
         // { path: 'list', component: ContactlistComponent },
         { path: 'configuration/forms', component: FormsComponent }
       ];

这是我的链接:

<a [routerLink]="/contact/list">List</a>
<a [routerLink]="/contact">Add New</a>

因此,当我点击这两个链接时,我的联系人链接正在打开。

在这里,当我这样做时,它起作用:

const routes: Routes = [
             { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
             { path: 'dashboard', component: HomeComponent },
             {
               path: 'contact', component: ContactComponent,              
             },
             { path: 'contact/list', component: ContactlistComponent },
             { path: 'configuration/forms', component: FormsComponent }
           ];

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要将pathMatch: 'full'添加到您的第一个子路线(具有空路径的路线),否则contact/list也将匹配第一条路线。

const routes: Routes = [
 { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
 { path: 'dashboard', component: HomeComponent },
 {
   path: 'contact', component: ContactComponent,
   children: [     
     {
       path: '',
       component: ContactComponent,
       pathMatch: 'full'
     }, 
     {
       path: 'list',
       component: ContactlistComponent
     },      
   ]

 },
 // { path: 'list', component: ContactlistComponent },
 { path: 'configuration/forms', component: FormsComponent }
];

答案 1 :(得分:1)

您可以使用此代码使用父路线

const routes: Routes = [
         { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
         { path: 'dashboard', component: HomeComponent },
         {
           path: 'contact', component: ContactComponent,children:ChilddataRoute


         },
         // { path: 'list', component: ContactlistComponent },
         { path: 'configuration/forms', component: FormsComponent }
       ];

您可以使用其他打字稿文件的子路径

export const ChilddataRoute: Routes = [
  { path: '', component: ContactComponent },
  { path: '/list', component: ContactlistComponent },
];