Angular Router, A Complete Guide – Part 1

Angular router simply allows users to move through different parts of your application as they interact with it.

Angular router works just like your web browser.

Think about how you interact with your browser – you go to different URLs to see different websites and you can move backward and forward through your browser history. The only difference in Angular is that you’re moving the user through different components within your single page application.

Now that you know the bare bone basics of Angular’s Router, it’s time to play with some code.

Get the Code

You can download the source code to follow along – git clone https://github.com/cartab/angular-router.

cd into the directory the project was cloned into and run npm install. You may need to use sudo depending on your permissions and configuration.

Now use ng serve to spin up the application on http://localhost:4200.

This a simple application that allows the user to move around different routes / places in his application / life. That includes his home, the office, the gym and his favorite restaurant. Play around with the routes for a bit, use the forward and back button on your browser and observe how the application behaves.

Angular Router Core Concepts

So how can you add routing to your application?

Base Href

First, you need to add the <base href="/"> tag in the <head> of your index.html file. That gives the Router the base URL for your routes. Adding this tag with the href="/" attribute tells the browser to load all routes relative to /.

This means that <a href="home">Home</a> would take us to /home.

If we set our base as such – <base href="/something/">, the same link would take us to /something/home.

That’s all you need to know about the base tag for now. You can read more about the base tag here.

Configuring Angular Router

The RouterModule is not a part of the core angular library, it’s optional. Not all applications require routing and some companies choose to use a custom or third party implementation instead of Angular router.

Having said that, let’s see how we can configure the router for our application. We will do this in a new file – app.routes.ts to keep the main app.module.ts file clean.

The components above – HomeComponent, WorkComponent, etc. are just placeholder components that display a simple message.

The RouterModule is what does the magic here. It has two static methods –

1. forRoot

We need to use this method at the root of our application. We can pass it the routes and any additional configuration (more on that in Part 2).

The forRoot method creates a module that contains, the routes, directives as well as the routing service. This is the key distinction between the forRoot and the forChild methods – the routing service.

This method should be used only once at the root of the application.

2. forChild

Similar to the forRoot method, the forChild method creates a module with routes and directives. We cannot pass this method any configuration options, or add it to the root. But, our application can have multiple routes imported with the RouterModule.forChild method.

The forChild method is useful when we want to add module specific routes to larger applications. We can then take advantage of lazy loading to speed up the initial load time of our application.

Now that we’ve understood the key difference between the forChild and the forRoot method, we can import the routes in our AppModule so that the app can recognize them when they appear in the browser’s address bar.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

// We don't surround this in curly braces because it is the default export in the app.routes.ts file

import appRoutes from'./app.routes';

// ... other imports

@NgModule({

// ...other config

imports:[

appRoutes,

// ... other imports

]

// ...other config

})

exportclassAppModule{}

Perfect!

We have our routes in place and they’ve all been imported into our main app module. But where do the components associated with a particular route get displayed?

RouterOutlet

Angular’s <router-outlet> directive is a placeholder which gets filled based on the current angular router state (the link in the address bar). This is where the components associated with a route get displayed.

Note: For now, we are building a simple application so we need only one router-outlet. As the application gets more complex, we can have multiple angular router outlets (even on the same page).

Let’s add the <router-outlet> to the app.component.html file.

Where do you want to go?

Our components will now be displayed under the <h1> heading. If you’re following along with the code, visit http://localhost:4200/work. You should see the work component template.

But wait!

Our users aren’t going to visit these routes by entering them into the address bar. We need to give them links to move around the application.

RouterLink

This directive allows us to link to different parts of our application. Think of this as a replacement for the href attribute.

Each anchor tag in the code above has the routerLink directive with the value set to the desired route.

If the user clicks on the work route, he will be sent to /work. We don’t need to add the / (backslash) everywhere because we’ve already specified that in the <base> tag.

We can also pass parameters to the routerLink directive. For example, if we wanted to redirect the user to /home/time/12;item=banana (to say that the user returned home at 12pm with a banana), we could do that with –

1

<a>Home at12</a>

There’s a lot more you can do with the routerLink directive. Click here to read more about how you can set query params and fragment in your routes.

RouterLinkActive

So what does the routerLinkActive directive do?

Depending on the application, we might want to change the styling of a link when it is active. That’s exactly what this directive does. It adds a class to the element when it’s corresponding route become active.

In our code, when we navigate to /home, the routerLinkActive will append btn-primary to the anchor tag’s class. This will separate Home from the other routes.

When the route changes, the btn-primary class will be removed and Home will return to its default style.

Final Notes

You now have everything you need to create basic routes for your application.

We will cover more advanced routing concepts such as nested routes, auxiliary outlets and lazy loading modules based on routes in Part 2 of this article.

If you’ve been following along with the code, here’s an exercise for you to sharpen your Angular routing skills –

Create another night-club route that in the core-life module and add it to the navigation.