Having nested children routes in an application is a very common way to present detailed information within a category. Routes inside Angular can be configured to have nested parent-child relationships in your route configuration.
Creating nesting routes in Angular
Getting ready
In our case, we may want to have a specific blog post route that is accessible by a unique ID under our /posts route. We will also need to provide a way to pass an ID parameter along to our component so that it can look up the details we would want to present to the user for that specific blog post.
How to do it...
To add a child route to our router module, we will need to update its route configuration:
- First, we must define children routes using the children property in the route configuration:
RouterModule.forRoot([
...
{
path: "posts",
component: PostsComponent,
children: [{
path: ":id",
component: PostComponent
}]
}
...
])
- Once we have set up our child route, we can retrieve our ID parameter in our new PostComponent.ts using the ActivatedRoute class from the Angular router:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from "@angular/router";
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
postId = null;
constructor(private route:ActivatedRoute) {
route.params.subscribe(
params =>{
this.postId = parseInt(params['id']);
}
);
}
}
- Now that we have the ID parameter, we can use it in our template:
<p>
post works! - {{postId}}
</p>
- Finally, we will also need to provide another outlet within the template of PostsComponent to surface our specific post template:
<p>
posts works!
</p>
<router-outlet></router-outlet>
How it works...
The children property of our /posts route configuration is itself a new router configuration that we can nest under a specific route in our root router configuration. By setting the path to :id, we are declaring that whatever value is passed as the next segment of the URI beyond /posts will be made available as a parameter in our controller known as params['id'].
We receive the route parameters from the router as an observable that must be resolved before we can retrieve the ID. This sort of asynchronous data handling will be something that we will explore more in Chapter 3, Working with Data, but for now suffice to say that this is just a means of resolving this property so that we have it available to our component. Since the ID parameter could, in theory, be any type of data, here we parse it into a number. We will need to add a case to handle when this result is invalid, but we will return to that problem in a future section.