Child routes

What is a child route? A child route is a concept where we say that a route has children. We could write the routes for a feature like this:

{
path : 'products',
component : ProductListComponent
},
{
path : 'products/:id',
component : ProductsDetail
},
{
path : 'products/:id/orders',
component : ProductsDetailOrders
}

What happens, though, if we want to have a products container component and in that component, we would like to have a product list or a product detail showing? For that case, we want to group our routes differently. We have clearly said that the Product container is the parent component that you should route to. So, it would be the first responder when going to the route /products. Let's start by setting up the products route. It should listen to /products URL and have the ProductsContainerComponent responding, like so:

{
path: 'products',
component : ProductsContainerComponent
}

Our other routes can be added as its children, like so:

{
path: 'products',
component : ProductsContainerComponent,
children : [{
path : '',
component : ProductListComponent
}, {
path: ':id',
component : ProductDetailComponent
}, {
path : ':id/orders',
component : ProductsDetailOrders
}]
}

Now, this might make more sense from an organizational viewpoint but there is a bit of a technical difference; the ProductsContainer will need to have its own router-outlet for this to work. So, a quick overview of our app so far would look like this:

/app . // contains router-outlet
/products
ProductsContainerComponent // contains router outlet
ProductListComponent
ProductDetailComponent
ProductsDetailOrders

The main driver for doing it this way is so that we can create a container to give that some header or footer information and render replaceable content, much like we can do with the template for the app component:

// ProductsContainerComponent template
<!-- header -->
<router-outlet></router-outlet>
<!-- footer -->

In summary the benefits to a container approach is the following:

  • Creating child routes means we can treat a feature landing page like a page view or a viewport, thereby we can define things such as a header, a footer, and a part of the page as a piece of content that can be replaced
  • We need to write less when defining the route path, the parent's route is already assumed
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset