Sometimes as our app grows in complexity we need to set up some nested routes (also known as child routes). We often want to do this so users can link to a deeper part of the app, which can't be done by just nesting a child component. In this lesson, you'll learn how to set up child routes in Angular.
Instructor: [0:00] Sometimes as our app grows in complexity, we want to be able to add nested or child routes. Here, I would like to be able to add a route to get to this info page and this items page. I'd like to have a route that the user can navigate to. That's why I don't want to just have a nested component.
[0:18] To do that, there's a few steps. We don't need any outside packages or libraries. The Angular router can do this for us.
[0:25] The first thing we need to do is go over to our AppModule. In our Routes array here, we're going to add a new property here. It's going to be an array called children. This array of children is composed of other route objects similar to what we already have. I can create a new object. Each object will have a path and component like our normal route objects.
[0:50] I'll say path, and let's give this a path of info. For my component here, I'm going to use the system info component that I've created.
[0:59] Now, let's just duplicate this whole object and add a comma and then instead of info here, let's call it items and then instead of system info component, we'll use the system items component that I've made.
[1:13] Now, our child routes are set up off of the system route, but we need to update our template to make this work. Let's go over to the system detail component template here and the first thing we need to do is add another router outlet to this page. We'll just say router outlet and then lastly, we need to get these links to work.
[1:33] For both of these links, what we'll do is we'll add in a router link. For the first one, we'll pass in info and for the second one, we'll pass in items and then for both of these router links, I want to tell the Angular router to give this an active class when it's the active route.
[1:51] To do that, I can for each of these links, just add a property called router link active and pass in the active class that I want to give it. Let me make this a little bit easier to see. I'll put these on some new lines here.
[2:06] Now, you can see I've got the router link active and I've got the router link here. Now, when I go in the browser, you can see that when I hover over info and items, I get the pointer cursor, and when I click on them, now I've got the info component and the items component.
[2:23] If I look at my URL bar, you can see that I've got the system/one/itemsroute, and if I click on info, I have the system/one/inforoute. You can also see that whichever route is active has that brown background and that's the active class that I've given it.
[2:43] That's how to set up child or nested routes in Angular.