How to load child route by default in angular 2
Add empty path routes as redirect automatically
const appRoutes: Routes = [ { path:'', redirectTo: 'a', pathMatch: 'full' }, { path: 'a', component: AComponent, children:[ { path:'', redirectTo: 'x', pathMatch: 'full' }, { path:'x', component: AXcomponent } ] }, { path: 'b', component: bComponent }];
The accepted answer is no good if your child route contains an outlet.
For example I am displaying an 'order' by ID and using a named outlet 'detail' for the summary as well as other panels.
/orders/5000001/(detail:summary)/orders/5000001/(detail:edit)
Because these URLS are so ugly I also wanted the following two to redirect:
/orders/5000001 => /orders/5000001/(detail:summary)/orders/5000001/summary => /orders/5000001/(detail:summary)
So I tried a componentless redirect in the child:
{ path: '', pathMatch: 'full', redirectTo: '(detail:summary)' }
This fails because a 'redirectTo' needs to be absolute (I'm sure there's a complex technical reason for this). So then I tried this:
{ path: '', pathMatch: 'full', redirectTo: '/order/:id/(detail:summary)' }
And that fails because :id
is not a named variable in the context of the child.
So in the end I figured this out:
children: [ { path: ':id', pathMatch: 'full', redirectTo: '/orders/:id/(detail:summary)' }, { path: ':id/summary', pathMatch: 'full', redirectTo: '/orders/:id/(detail:summary)' }, { // this goes in the main router outlet path: ':id', component: OrderFulldetailsComponent, children: [ { path: 'summary', component: OrderSummaryComponent, outlet: 'detail' }, { path: 'edit', component: OrderEditComponent, outlet: 'detail' } ] } ]
Note it is important to do pathMatch: 'full'
on path: ':id'
or it will match when you hit /:id/(detail:summary)
and go nowhere.