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
I had the same issue. This is how I fixed it:
const routes: Routes = [
{
path: '',
children: [
{
path: '',
component: ParentComponent,
},
{
path: 'child',
component: ChildComponent,
}
]
}
];
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With