Angular 2 条子路由

Angular 2 Child Route

我是这样配置路由的:

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

这是我的 links:

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

因此,当我同时单击两个 link 时,我的联系人 link 就会打开。

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

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

我做错了什么?

您需要将 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 }
];

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

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

您可以将子路由与另一个 Typescript 文件一起使用

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