Angular 2+ has a neat way to deal with child routes but those coming from AngularJS may find them a bit confusing. In this post, I will show how to use them with <router-outlet></router-outlet>
for a seamless experience.
First, lets take a look at an abbreviated version of the app-routing.ts file.
const appRoutes: Routes = [ { path: 'product/:id', component: ProductComponent, children: [ { path: 'detail', component: ProductDetailComponent }, { path: 'reviews', component: ProductReviewsComponent } ] } ];
In this excerpt, there is a parent route, product/:id. This route has two different child routes: detail and reviews which will match the paths product/:id/detail and product/:id/reviews. Easy enough. However, getting them rendered correctly is the trick but very easy once you understand what is expected. The parent route is also a top level route, which means that the top level template will need a single <router-outlet></router-outlet>
tag.
Then, in the template hooked to the parent product route will also need a single <router-outlet></router-outlet>
tag. The second router-outlet tag will be used to render details and reviews. As an example:
<h3>{{product.Name}}</h3> <router-outlet></router-outlet>
I like to keep these rules in mind when dealing with routes and outlets:
- My top-most app template will have a single router-outlet tag that will be used to render all top-level routes.
- Each top-level route that has children will need a router-outlet tag in it’s own template.
That is all there is to it. I feel that this convention is a drastic improvement over the routing used in AngularJS.