How to create navigation in Angular 9 Application using Angular Router

This article will demonstrate the proper way to create page navigation leveraging routing features provided by the Angular 9 framework.

1 — Create a new Angular 9 application

First let’s create a simple Angular 9 application which we will use for the demonstration purposes of how to create page navigation.

If you want a detailed step-by-step tutorial showing you how to create a new Angular 9 application, I have written an article that details the process. You can see it here:

Run the following command in you VScode terminal:

ng new Navigation

and follow the prompts on the screen. When prompted with the following question:
“Would you like to add Angular routing? (y/N)”
You need to choose the yes option. This will include the AppRoutingModule and imports it into the AppModule of the Angular application. If you accidentally chose no, you can always add it after the fact via the CLI using the following command:

ng generate module app-routin --flat --module=app

Creating the application will take few minutes to download all of the necessary dependencies. Once the application is completed successfully you will get a prompt in the terminal indicating so.

2 — Test

As noted previously, the AppRoutingModule is automatically included in the app.module.ts file. This makes the AppRoutingModule available application wide. In the screenshot below you will notice that the AppRoutingModule is included in the imports inside the @NgModule decorator.

image 1 goes here

Additionally, a new src>app>app-routing.module.ts file is created in the application solution. This file will serve the purpose of defining our routes in our application.

3 — Create multiple components in our application

To have a working example that properly demonstrates navigation between multiple components/pages we need to create components in our application. Let us create the following three components:

  • Home
  • About Us
  • Contact Us

To create the components run the following commands in the application terminal:

ng g c home

and

ng g c aboutus

and

ng g c contactus

Those commands will create three new folders: src>app>home, src>app>aboutus and src>app>contactus along with their corresponding files as shown in the screen shot below:

Each component will represent a new “page” for us. So far our application should have four components:

  • app component
  • home component
  • aboutus component
  • contactus component

4 — What are the Fundamental building blocks for routes

In Angular 9 there are three fundamental building blocks to creating a route.

  1. Import the AppRoutingModule into AppModule and add it to the imports array
    As mentioned previously in step 1, the Angular CLI performs this step automatically. The CLI also sets up an empty Routes array for your routes and configures the imports and exports arrays for @NgModule().
  2. Define your routes in your routes array
    Each route in this array is a JavaScript object that contains two properties. The first property, path, defines the URL path for the route.
    The second property, component, defines the component Angular should use for the corresponding path.

3. Add your routes to your application
This third building block is where routes can be added to the application.

Important Note:

The order of routes is important because the Router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes.

List routes with a static path first, followed by an empty path route, which matches the default route. The wildacrdcourte, “*”, must come last because it matches every URL and the Router selects it only if no other routes match first.

5 — Setting up the routes in our application

Now that we have a quick understanding of the fundamental building blocks for routes in Angular let’s set up our routes for the components that we have created.

Open the src>app>app-routing.module.ts file and let us modify the Routes array by adding three routes to it as such:

const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", component: HomeComponent },
{ path: "aboutus", component: AboutusComponent },
{ path: "contactus", component: ContactusComponent },
{ path: "*", component: HomeComponent },
];

The code in the src>app>app-routing.module.ts should look lie the screen shot below at this point:

6 — Create navigation menu and set up the router-outlet on the AppComponent

In order to make navigation work we need to create the navigation menu and add the router-outlet component.

Open the src>app>app.module.html file and remove all of its contents. Once the file is empty you need to copy the following HTML and paste it in the the file:

<ul>
<li>
<a routerLink="/home">Home</a>
</li>
<li>
<a routerLink="/aboutus">About Us</a>
</li>
<li>
<a routerLink="/contactus">Contact Us</a>
</li>
</ul>
<router-outlet></router-outlet>

At this point the app.module.html file should look like this:

Notice the <router-outlet></router-outlet> tag in the file? This refers to the app-routing.module.ts file that was created during the creation of the application when we specified to include the AppRoutingModule.

Router-outlet in Angular works as a placeholder which is used to load the different components dynamically based on the activated component or current route state. The routed component will appear under the <router-outlet>.

7 — Build and run the application

At this point we should have a running application with proper routing/navigation. To test our implementation we need to build and run our Angular application. Run the following command in the application Terminal:

ng serve -o

The application will open up in a new browser tab and should look like this:

Notice that on initial load of the application the Home page is loaded and if you look at the URL you will notice the “/home”. This is mainly because of the following entry in our Routes array:

This entry tells the routing engine that if no routes has been provided to the URL then the main component to load should be the “HomeComponent”. The default page can be anything you specify it to be.

Now try clocking on the “About Us” link and you should see the About Us component get loaded on the screen.

If you click on the “Contact Us” link then the Contact Us component will be loaded.

NOTE:

By using the routerLink, the router service will track the history, and back and forwrd buttons will work in your browser.

Now after you performed the two routing operations try to click on the back button on your browser. You will notice that you are routed to the previously visited link which was the contact us. Next try to click the forward button in your browser. You will notice that you have been redirected to the contact us page.

8 — How to append a parameter to your route?

To add a parameter to a route in our angular application we must add a new entry in the Routes array. To demonstrate this, let’s work with the following example: Let us assume that the Contact Us page can be loaded with and without a parameter. If a parameter “id” is provided in the URL, then we will display the provided parameter on the screen; otherwise we will not display/print to the screen the parameter.

To do this, we must make the following changes to the src>app>contactus.component.ts file

First we need to inject the ActivatedRoute service in the Contact Us component via the constructor. Then we will need to create a class level variable “id” which will hold the id passed in as a parameter int he URL if applicable.

You will also notice that inside the ngOnInit() function we are subscribing to the route.params and extracting the id parameter from the params dictionary.

Next we will need to add a new route entry which supports a parameter in the Routes array inside the src>app>app-routing.module.ts file.

Add the following entry to the Routes array:

{ path: "contactus/:id", component: ContactusComponent }

Next, let’s add the following new link in the src>app>app.component.html

<li>
<a [routerLink]="['/contactus', 123]">
Contact Us with parameter</a>
</li>

The src>app>app.component.html should now looks like the following screen shot:

Notice the brackets around [routerLink] and its value? This is how we specify that this link uses parameter.

Next, let’s modify the src>app>contactus.component.html file and add some HTML to print out the id parameter value when applicable.

Now let’s build and run the application again. Once the application is running, click on the “Contact Us without parameter”. You will notice that no value is printed out after the “This is the ID passed in the parameter:”. That is normal since we did not specify any parameter to be included.

When you click on the “Contact Us with parameter” link you will notice that the “123” value is displayed onto the screen.

Now if you click in the URL section and manually change the value to be “ThisIsManuallyChanged” you will notice that it was reflected right away on the screen as shown in the screen shot below.

9 — Conclusion

To conclude I would like to mention that in a single-page app, you change what the user sees simply by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. In order to make this feasible Angular made it easy by leveraging the Router.

I hope this tutorial was helpful to you, if you have any questions regarding this article please leave a comment below. Also do not hesitate to leave your feedback. Your responses will help improve the quality of these articles.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store