Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 route with url parameter conflicts with other routes

My child module routes are as follows,

{
  path: '',
  children: [
    { path: '', component: TripManagerComponent },
    { path: ':id', component: TripDetailComponent },
    { path: 'new', component: TripNewComponent }
  ]
}

I am navigating to these routes as follows,

navigateToTrip(index: number) {
  this.router.navigate([index], { relativeTo: this.route });
}

navigateToNewTrip() {
  this.router.navigate(['new'], { relativeTo: this.route });
}

But Angular detects new route as :id and navigates me to TripDetailComponent.

The problem here is Angular detects 'new' string as url parameter for :id route.

I could add a prefix to :id, i.e. view/:id and make this work. But, I need to keep the url pattern as it is. Is there a way to do this?

My expected url pattern is,

/trips        --> show all trips
/trips/2334   --> show details of trip 2334
/trips/new    --> show a form to create a new trip
like image 378
charith.arumapperuma Avatar asked Nov 08 '16 20:11

charith.arumapperuma


1 Answers

Currently you :id route matches also with new and the router doesn't look further for other matching routes.

The order is relevant. Move the new route before the :id route, then the new route matches before the :id route.

{
  path: '',
  children: [
    { path: '', component: TripManagerComponent },
    { path: 'new', component: TripNewComponent }
    { path: ':id', component: TripDetailComponent },
  ]
}
like image 103
Günter Zöchbauer Avatar answered Nov 08 '22 00:11

Günter Zöchbauer