Defining Child Routes
When some routes may only be accessible and viewed within other routes it may be appropriate to create them as child routes.
For example: The product details page may have a tabbed navigation section that shows the product overview by default. When the user clicks the "Technical Specs" tab the section shows the specs instead.
If the user clicks on the product with ID 3, we want to show the product details page with the overview:
localhost:3000/product-details/3/overview
When the user clicks "Technical Specs":
localhost:3000/product-details/3/specs
overview
and specs
are child routes of product-details/:id
. They are only reachable within product details.
Our Routes
with children would look like:
Where would the components for these child routes be displayed? Just like we had a <router-outlet></router-outlet>
for the root application component, we would have a router outlet inside the ProductDetails
component. The components corresponding to the child routes of product-details
would be placed in the router outlet in ProductDetails
.
Alternatively, we could specify overview
route URL simply as:
localhost:3000/product-details/3
Since the Overview
child route of product-details
has an empty path, it will be loaded by default. The specs
child route remains the same.
View Example with child routes
View Example with route params & child routes
Accessing a Parent's Route Parameters
In the above example, say that the child routes of product-details
needed the ID of the product to fetch the spec or overview information. The child route component can access the parent route's parameters as follows:
View Example child routes accessing parent's route parameters
Links
Routes can be prepended with /
, or ../
; this tells Angular where in the route tree to link to.
Prefix
Looks in
/
Root of the application
none
Current component children routes
../
Current component parent routes
Example:
In the above example, the link for route one links to a child of the current route. The link for route two links to a sibling of the current route. The link for route three links to a child of the root component (same as route one link if current route is root component).
Last updated