Search code examples
angulartypescriptangular-router

How to create optional router argument in angular 7


I am have a router configuration shown below.

const routes: Routes = [
  {
    path: 'Registration',
    component: RegisterComponent,
    children: [
      { path:'',component:ProfileComponent},
      { path: 'Dependent', component: DependentComponent },
      { path: 'Matrimony', component: MatrimonyComponent },
      { path: 'Subscription', component: MagazinesubscriptionComponent },
      { path: 'Donation', component: DonationComponent }
        ]
  },
  {
    path: 'Profile',
     component: ProfilelistComponent
    //component: VoteprofileComponent
  }
];

This same router i want to use for editing. Mean like shown below.

const routes: Routes = [
  {
    path: 'Registration/:id',
    component: RegisterComponent,
    children: [
      { path:'',component:ProfileComponent},
      { path: 'Dependent', component: DependentComponent },
      { path: 'Matrimony', component: MatrimonyComponent },
      { path: 'Subscription', component: MagazinesubscriptionComponent },
      { path: 'Donation', component: DonationComponent }
        ]
  },
  {
    path: 'Profile',
     component: ProfilelistComponent
    //component: VoteprofileComponent
  }
];

Is there anyway in angular without replicating the complete route config I can achieve.

Mean i can specify the parameter as optional?


Solution

  • I don't know of a way to make the parameter optional. Depending on what you're trying to achieve you could use a specific string you could detect in the id param (Registration/new vs Registration/678A6).

    Anyway the routes are just plain typescript so I guess you could keep it dry this way:

    const registrationRouteConfig = {
      component: RegisterComponent,
      children: [
        { path:'',component:ProfileComponent},
        { path: 'Dependent', component: DependentComponent },
        { path: 'Matrimony', component: MatrimonyComponent },
        { path: 'Subscription', component: MagazinesubscriptionComponent },
        { path: 'Donation', component: DonationComponent }
      ]
    }
    
    const routes: Routes = [
       { path: 'Registration', ...registrationRouteConfig },
       { path: 'Registration/:id', ...registrationRouteConfig },
       { path: 'Profile', component: ProfilelistComponent }
    ]