36
votes

Is there a way to display a child route in the parent route's <router-outlet>?

For example, let's say we have two routes:

/users/12345

/users/12345/orders/12345

I need the second to be a child of the first, but I also need to completely replace the contents of /users/12345 with the contents of /users/12345/orders/12345 opposed to having /users/12345/orders/12345 in the /users/12345 sub router-outlet.

I thought I could do this by just naming the parent level router-outlet and have both routes target it, but from the research I've been doing (and the errors it caused) I get the feeling the names were intended for secondary uses when there already exists a primary router-outlet

5

5 Answers

26
votes

I had the same issue. This is how I fixed it:

const routes: Routes = [
   {
    path: '',
    children: [
         {
           path: '',
           component: ParentComponent,
         },
         {
           path: 'child',
           component: ChildComponent,
         }
     ]
   }
];  
21
votes

You can do it by setting your routes like this :

const routes : Routes = [
  { 
    path : 'user/:id',
    component : ParentComponent,
    children : [
      { path : '', component : UserComponent },
      { path : 'order/:id', component : OrderComponent }
    ]
  }
]

ParentComponent's template will have only the <router-outlet> to load its children.

11
votes

If you need to hide something (like a datagrid, or instruction panel) based upon a child route being active you can simply use this:

<div *ngIf="outlet.isActivated == false">
   Please select a child route!
</div>

<router-outlet #outlet="outlet"></router-outlet>

It is important to include #outlet="outlet" with the quotes because you're exporting a template variable reference.

There are also events on router-outlet for activation and deactivation.

An alternative is to get the child route when the NavigationEnd event occurs, and then make decisions what to show or hide. For simpler cases the first approach should work fine.

Also not relevant to your question I don't think, but you can completely hide a router-outlet with an *ngIf as you would anything else.

5
votes

edit: I've come up with a new solution revolving around using template directives that allows for setting up routes hierarchically opposed to at the same level.

The sample code/demo can be found here: https://stackblitz.com/edit/angular-routing-page-layout

Updated version (2019): https://stackblitz.com/edit/angular-routing-page-layout-cnjpz8

4
votes
 let routes = [
  { 
    path: 'users/:id',
    component: UsersComponent
  },
  {
    path: 'users/:id/orders/:id',
    component: OrdersComponent
  }
 ];