1. 1
    Define and configure a route with the Angular router
    2m 36s
⚠️ This lesson is retired and might contain outdated information.

Define and configure a route with the Angular router

Share this video with your friends

Social Share Links

Send Tweet

Components are first class citizens in an Angular application. Therefore, naturally each route points to an Angular component which gets activated whenever that route is triggered. In this lesson we will learn how to define such “routing components”, how to configure them on our router and how to activate them accordingly. Note, the router has been already installed using npm install @angular/router --save.

Instructor: [00:00] This is a very simple Angular application where I'm having here two components. They are already registered within our ng module. Let's go back here to our app component HTML and quickly instantiate both of them. You can see they get rendered on the page correctly.

[00:19] Assume these represent different kind of states our application might be in. When the user navigates to the home part of our application, we want to show this component. When he wants to get information about our application, we want to show this component.

[00:32] Obviously, we could do this with some kind of ng-if statements and then switch the components on and off, but that is obviously not scalable when our application gets more and more components.

[00:43] Rather, what we want to do is to use the routing mechanism. We have the router already installed. The first step is to import a RouterModule directly from Angular's router package. Next, we can go down here in the module section and use the RouterModule.forRoot, where we then register different kind of routes.

[01:09] Obviously, those routes need to be defined. Let's create here an array. Let's also import here the correct types, always from the router package, and define our first route. Let's say whenever the user navigates to home, we want to show the home component.

[01:33] As you can see here, I am defining here a path which defines the URL, which the router has to verify. Once the URL is matched, he should activate this component. Similarly, whenever the user navigates to the about, we want to show the about component. Now, let's save this.

[01:51] We also need to reference these routes here in the RouterModule configuration. From that point of view, the setup is done. We need to do a final part, which is to go in our app component and specify where those dynamic routing components should be inserted. For that purpose, we can use the RouterOutlet.

[02:12] Now, when we change the URL to go to home, you can see that the home component gets activated. In fact, if we inspect here, we can see here the RouterOutlet. Just below the RouterOutlet, the component will get inserted by the router dynamically. Similarly, if we change to about, the about component gets inserted dynamically below the RouterOutlet.