The RouterLink Directive

In this lesson, we'll learn how to use the RouterLink directive to navigate around the application.

We'll cover the following...

At the moment, the only way we can navigate around the application is by manually typing the path in the URL. The next thing we’ll tackle is creating some links that we can use to navigate to the other pages.

We installed Bootstrap, which comes with some classes for creating a navigation bar. You can find more information about those classes here.

We’ll be using it to help us create the links. Also, we’ll be using Bootstrap to help us center the page content. Update the app.component.html file to the following:

# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries

# For the full list of supported browsers by the Angular framework, please see:
# https://angular.io/guide/browser-support

# You can see what browsers were selected by your queries by running:
#   npx browserslist

last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.

In the widget above, we’re mostly using Bootstrap. The <router-outlet> element is being wrapped with some classes to help center and space it.

The links aren’t using anything special. They’re standard links with href attributes telling the browser to navigate to the other pages.

If we run the example, everything works, but there is one problem. Every time a link is clicked, the browser will refresh the page. The assets for the browser will need to be reloaded.

The history API

The Angular Router can use the history API to navigate around the application.

What is the history API?

The history API enables us to visit different pages without having to reload the assets. This is achieved using the history.pushState() method. It exposes the browser’s navigation history to JavaScript.

If you’d like to learn more about the history API, then check out this link.

We’ll want to use it to make loading pages faster. Luckily, we don’t have to do anything to enable the history API. It’s automatically leveraged by Angular. The only thing we need to do is update the <a> element’s href attribute to the routerLink directive.