How to create Nested or Child routes in Angular?
This Article helps you to Understand, How to create Nested or Child routes in Angular?
Routes within other routes are known as nested routes. We'll demonstrate how to build a child route and display the child components in this tutorial. We can successfully create a tree of routes using Angular's ability to nest child routes under other child routes.
Here the ServerComponent is defined as the sibling of the ServersComponent and not as the child
To make the ServerComponent as the child of the ServerComponent , we need to add the children key to the servers route, which is an array of all child routes
The child route definition is similar to the parent route definition. It has a path and component that gets invoked when the user navigates to the child route.
In the above example, the parent route path is ‘servers’ and the child route is ‘id’ and "id/edit"
This is will match the URL path “/servers/1” or "/servers/1/edit"
When the user navigates to the “/servers/id”, the router will start to look for a match in the routes array
Display the component using Router-outlet
The components are always rendered in the <RouterOutlet> of the parent component.
For ServerComponent the parent component is ServersComponent and not the AppComponent
Hence, we need to add <router-outlet></router-outlet> in the servers.component.html as shown below
ServerComponent / Child Component
Since both Server and ServerEdit component shares the same parent on clicking Edit, the ServerComponent get replaced with EditServerComponent
Nesting Children’s under a child
We can add child routes to a child route.
Mapping the action to View
When binding a path to the routerlink directive, we use a relative path. A forward slash (/) marks the start of an absolute path. When utilizing a relative path, the router will create the final URL by adding the path to the parent route path.
Both ProductOverviewComponent & ProductSpecComponent are rendered inside the ProductDetailComponent. Hence we need to add <router-outlet></router-outlet> in the Template of ProductDetailComponent.