Angular Routing Tutorial with Example

In this Angular Routing Tutorial, we look at how navigation & Routing works in Angular using the Angular Router. In this tutorial we will learn what Angular Routing is and how it works. We will also look at various components that make up the Angular Router Module. Then we will learn how to setup and configure the router. Finally, we will create a Angular Routing Example application with four components and create menu navigation system using the Angular Router.

Applies to: Angular 2 to the latest edition of i.e. Angular 8. Angular 9, Angular 10

You can download the source code from GitHub from the folder Routing

What is Routing

Routing allows you to move from one part of the application to another part or one View to another View.

The Angular Router Module

The Router is a separate module in Angular. It is in its own library package, @angular/router. The Router Module provides the necessary service providers and directives for navigating through application views.

Using Angular Router you can

  • Navigate to a specific view by typing a URL in the address bar
  • Pass optional parameters to the View
  • Bind the clickable elements to the View and load the view when the user performs application tasks
  • Handles back and forward buttons of the browser
  • Allows you to dynamically load the view
  • Protect the routes from unauthorized users using Guards

Components of Angular Router Module

Router

The Angular Router is an object that enables navigation from one component to the next component as users perform application tasks like clicking on menus links, buttons or clicking on back/forward button on the browser. We can access the router object and use its methods like navigate() or navigateByUrl(), to navigate to a route

Route

Route tells the Angular Router which view to display when a user clicks a link or pastes a URL into the browser address bar. Every Route consists of a path and a component it is mapped to. The Router object parses and builds the final URL using the Route

Routes

Routes is an array of Route objects our application supports

RouterOutlet

The outerOutlet is a directive (<router-outlet>) that serves as a placeholder, where the Router should display the view

RouterLink

The RouterLink is a directive that binds the HTML element to a Route. Clicking on the HTML element, which is bound to a RouterLink, will result in navigation to the Route. The RouterLink may contain parameters to be passed to the route’s component.

RouterLinkActive

RouterLinkActive is a directive for adding or removing classes from an HTML element that is bound to a RouterLink. Using this directive, we can toggle CSS classes for active RouterLinks based on the current RouterState

ActivatedRoute

The ActivatedRoute is an object that represents the currently activated route associated with the loaded Component.

RouterState

The current state of the router including a tree of the currently activated routes together with convenience methods for traversing the route tree.

RouteLink Parameters array

The Parameters or arguments to the Route. It is an array which you can bind to RouterLink directive or pass it as an argument to the Router.navigate method.

How to configure Angular Router

To Configure the Router in Angular, you need to follow these steps

  • Set the <base href>
  • Define routes for the view
  • Register the Router Service with Routes
  • Map HTML Element actions to Route
  • Choose where you want to display the view

Set the <base href>

The HTML <base> element specifies the base URL to use for all relative URLs contained within a document.

The Angular Router uses the HTML5 style of Routing (or PathLocationStrategy) as the default option. The router makes use of the browser’s history API for navigation and URL interaction.

To make HTML5 routing to work, we need to set up the “base href” in the DOM. This is done in app’s index.html file immediately after the head tag.

Define the routes

Next, create an array of route objects. Each route maps path (URL Segment) to the component

Where

path: The URL path segment of the route. We will use this value to refer to this route elsewhere in the app

component: The component to be loaded.

This route tells angular to render ProductComponent when the user navigate to the URL “/product”

Register the Routes

Import the Router Module from @angular/router library in the root module of the application

Then, install the routes using the RouterModule.forRoot method, passing the routes as the argument in the imports array

Map Action to Routes

Next, we need to bind the click event of the link, image or button to a route. This is done using the routerlink directive

The routerLink directive accepts an array of route names along with parameters. This array is called as Link Parameters array.

When the application requests navigation to the route “product”, the router looks in the routes array and activates the instance of the component associated with the route “product”, which is ProductComponent. The browser address location & history is also updated to /product

Choose where you want to display

Finally, we need to tell the angular where to display the view. This is done using the RouterOutlet directive as shown. We will add the following directive to the root component.

Angular Router: Sample Application

Let’s build a sample application with four components and build a navigation system to route for each one of them

HomeComponent: This component will display the Welcome message. This is also our default component.

ContactComponent: Displays the contact message.

ProductComponent: Displays the list of products. The Products are retrieved from the Angular 2 Service using Dependency injection.

ErrorComponent: The ErrorComponent is displayed, when the user navigates to a nonexistent path. This is basically a 404 error page.

Product Service

Index.html

Note the <base href=”/”> right after the head tag. This makes the browser know where is the root of our application is and helps it to construct the URL’s

Routes

Now, we have our components ready. The next step is to create our routes.

It is good practice to create all our route configuration in a separate file. So create app.routes.ts under the app folder.

First, we import Routes from router module

Next, we need to import all the components, that requires routing We have imported Home, Contact, Product, and Error Components

Finally, we have defined a constant (appRoutes) that contains the Routes that we wish to create. The Routes is an array of route configuration object (or route object).

Each route has several configurable properties.

Our First route is

The first parameter is the path, which represents the URL path segment. The second parameter is the component to display. The above route configuration means, when you navigate to /home (URL path segment), then the HomeComponent gets displayed.

Note that path does not contain the leading slash

The next two routes are similar to the home route

Default Route

The fourth route is

The path is empty, indicates the default route. The default route is redirected to the home path using the RedirectTo argument. This route means that, when you navigate to the root of your application /, you are redirected to the home path (/home), which in turn displays the HomeComponent.

Note, that we have pathMatch argument set to ‘full’. The pathMatch tells the Router how to match the URL.

When it is set to full, the path is matched to the entire URL

Every route ends in an empty space for ex: /contact/’’. If pathMatch is not set to full then the router will apply the redirect, which results in the error.

Wild Card Route

The next route is wildcard route

The “**” matches every URL. The Router will display the ErrorComponent.

Order matters: First one wins

Note that the order of the route is important. The Routes are matched in the order they are defined. The Router always returns the first matching route (first-match-wins strategy)

Since the wildcard route (**) matches every URL and should be placed last.

Now, we have set up our routes. Now we will add these routes to our application.

Register the Routes

Routes are registered in root module of the application. I.e. app.module.ts

First, we import the RouterModule

Next, import all the components

Next import the routes, which we configured from app.routes

Finally, we add the RouterModule to the import array, passing the routes we have configured via the forRoot method

Note that we are using the forRoot method.

the forRoot method is used, when you want to provide the service and also want to configure the service at the same time

The routermodule.forroot method returns the Router Service configured with the routes passed in the argument and also registers the Router service. It also registers the other providers that the routing module requires.

When the application is bootstrapped, the Router service looks at the current browser URL and performs the initial navigation.

When the user changes the URL either clicking on a link in the page or by entering a URL in the address bar, the router looks for a corresponding Route from the Routes array and renders the associated component.

Defining The Navigation

The next step is to define the navigation

Open the app.component.html. The AppComponent is only handling navigation. It will display the menu option, which user can click to navigate to a view

We are using bootstrap to style our component

We use the routerLink directive to bind anchor tag elements to the route

RouterLink is an attribute directive. We enclose it a square bracket. The routerLink is then bound to template expression, which returns a link parameters array.

The Link Parameters array is the Parameters or arguments to the Route. The Angular Router module constructs the URL using the link parameters array

When the user clicks on the link, the Router service uses the path to locating the route associated with the path and activates the component

Display the component using Router-outlet

Finally, we need to tell Angular where to display the Component. This is done using the Router-outlet directive

The RouterOutlet is a directive that tells the Angular where in our page we want to display the view.
We do not have to import the RouterOutlet and RouterLink directives. These directives are imported when we imported RouterModule in our app.module

That’s it

Running the Application

Type the in the address bar http://localhost:4200, you should see the HomeComponent is rendered, which is the default root

Type the invalid URL and you should see the ErrorComponent rendered.

Click on the menu options or Type the Back & forward button in the browser. Everything should work as intended.

Conclusion

In this tutorial, we learned to what is angular router is and learned how to use it, by creating a sample application.

3 thoughts on “Angular Routing Tutorial with Example”

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top