Praveen Rawat
Praveen Rawat

Reputation: 658

Angular 2 Child Route

I have configured my routing like this:

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

Here is my links:

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

So when I click on both links my Contact link is getting open.

Here, when i do this it works:

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

What i am doing wrong here?

Upvotes: 0

Views: 62

Answers (2)

Kasunjith Bimal
Kasunjith Bimal

Reputation: 188

You Can Use Parent Route Using this Code

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

You Can Use Child Route With Another Typescript File

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

Upvotes: 1

Brother Woodrow
Brother Woodrow

Reputation: 6382

You need to add pathMatch: 'full' to your first child route (the one with the empty path), or else contact/list will also match the first route.

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

Upvotes: 2

Related Questions