Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Have Child Route Component Replace Parent in router-outlet

Tags:

angular

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

like image 530
John Avatar asked Mar 16 '17 18:03

John


4 Answers

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

const routes: Routes = [
   {
    path: '',
    children: [
         {
           path: '',
           component: ParentComponent,
         },
         {
           path: 'child',
           component: ChildComponent,
         }
     ]
   }
];  
like image 82
N. berouain Avatar answered Oct 18 '22 21:10

N. berouain


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.

like image 36
YounesM Avatar answered Oct 18 '22 21:10

YounesM


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.

like image 14
Simon_Weaver Avatar answered Oct 18 '22 20:10

Simon_Weaver


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

like image 5
John Avatar answered Oct 18 '22 22:10

John