When we nest a route as a child route, we declare to Angular that it must be surfaced through a router-outlet inside our parent component. Depending on the context of our application, that might be what we want, but what if we wanted to render the component at the root level of our application? This is a case where a sibling route with a nested path would be more appropriate.
Creating sibling routes in Angular
How to do it...
Let’s take a look at the following code to create module with sibling routes:
- First, we will generate a new module for controlling our sibling routes. This will be useful in future chapters of this book for isolating the routing control for our blog posts:
ng generate module posts
- Instead of defining our related route as a child of "posts", we will define it at the same level. To distinguish the route for Angular we will provide the :id dynamic segment:
...
@NgModule({
imports: [
...
RouterModule.forRoot([{
path: "posts",
component: PostsComponent
}, {
path: "posts/:id",
component: PostComponent
}])
...
})
export class PostsModule { }
- Now when Angular resolves the route, if it doesn't have any dynamic segments it will be served by PostsComponent, otherwise it will end up being served by PostComponent.
How it works...
Here, we can see that both PostsComponent and PostComponent are at the root of our router configuration. However, the path for PostComponent is nested one level deeper to /posts/:id, so it will display as a nested URI in the browser. This approach will only allow PostComponent to be served in our root router-outlet, instead as a child of PostsComponent.
With that, we can now navigate to /posts/123, and we will see our post template rendering on the page with the post works - 123 text. By changing the URL to /posts/456, we will see that our id parameter updates to show us the text post works - 456. However, if we put in /posts/foobar, we will see our page render with the text post works - NaN due to a type conversion failure. In the next section, we will validate and properly handle this case.
There's more...
Another valid way to approach child routing is through the use of modules and the forChild method of the RouterModule. This approach lets any given module manage its own child routing tree under the root module's router:
...
RouterModule.forChild([
{
path: 'posts',
component: PostsComponent,
children: [{
path: ':id',
component: PostComponent
}]
}
])
...
A good reason to choose modular routing over simply nesting child routes in your root module is to keep your routing configuration clean and decoupled from the deep nesting of routes. Modular routes are easier to refactor and manage as your application grows, whereas simple nested children route configurations are a bit easier and faster to implement.