How to Detect Route Change in Angular?

Detecting a route change in Angular can be quite useful in various situations, for example, you could use the route change detection to show/hide or highlight the navigation menu if you navigate to a specific route.

There could be other reasons as well, for example, you could show the loading spinner whenever there is a change in the route and hide it when the user is routed to the new route successfully. OR, you could use it to preload the data for the next route before the user navigates to it.

In this article, I will show you an easy way to detect if there is a route change in Angular. We will also cover how we can detect if the user gets an error while navigating to a route.


Detecting the Route Change

When we navigate to a route in Angular, certain router events are fired in a particular sequence until the user successfully navigates to that route.

The first router event that is fired as soon as you click on a router link is the NavigationStart. This event is emitted before the router begins the navigation process.

After the NavigationStart, there are a lot of other events that are fired by Angular such as RoutesRecognized, GuardsCheckStart, ChildActivationStart and so on until the user successfully navigates to that route.

The last router event which is fired by the Angular router is the NavigationEnd. This event is fired when the user successfully navigates to the route. If there is an error while navigating to the given route eg. the route is not found, or there is a network error, the NavigationError event is fired by the Angular router.

So, long story short, we just need the NavigationStart, NavigationEnd and the NavigationError router events to detect any route change in Angular. Let’s try to implement it in our project.

For demonstration purpose, I have created an Angular app which contains three routes, /home, /one, /two. Inside the app component, I have also created a raw navbar to navigate these routes.

Inside the app.component.ts file, I have subscribed to the router events to detect the route change:

import { Component } from '@angular/core';
import { NavigationEnd, NavigationError, NavigationStart, Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-basics';
  currentRoute = '';

  constructor(private router: Router) {

    // Subscribe to the router events
    this.router.events.subscribe((event:any)=>{

      if(event instanceof NavigationStart){
        console.log('Router navigation started');
      }

      if(event instanceof NavigationEnd){
        console.log('Router navigation ended');
        this.currentRoute = event.url;  // Get the current Route
      }

      if(event instanceof NavigationError){
        console.log('Router navigation Failed');
      }
    })

   }

}

And below is our app.component.html file with a raw navbar that has the three routes(/home, /one & /two):

<!-- app.component.html file -->
<nav>
    <ul>
        <li>
            <a routerLink="/home">Home</a>
        </li>
        <li>
            <a routerLink="/one">Component One</a>
        </li>
        <li>
            <a routerLink="/two">Component Two</a>
        </li>
    </ul>
</nav>

<div>
    <h2>Route change detected, New route is: <b>{{currentRoute}}</b></h2>
</div>
<router-outlet></router-outlet>

After running the above code, you will get the following output:

Detect route change in Angular

Code Explanation:

In the above example, we first injected the Angular router into the constructor of our app component so that we can subscribe to its events.

Next, inside the constructor, we subscribed to the router events to keep a track of the router events such as NavigationStart, NavigationEnd, NavigationError, etc. that get fired on navigating to a route.

When the navigation process starts, the NavigationStart event is fired. This lets us know that there is a change in the route. But, will this route change be successful or not depends on several factors such as route availability, network connection, etc.

As soon as the navigation process finishes i.e. the user successfully navigates to a route, the NavigationEnd event is fired and we update the currentRoute variable with the url property of the event object.


Detect Navigational Errors

While navigating to a route, you might get navigational errors, for example, the route you are trying to visit is not available, or there is a network connection problem. In such situations, we can show an alert message to the user that there is something wrong.

So, If you want to handle the navigational errors, you can put that code inside the NavigationError event’s block:

if(event instanceof NavigationError){
  console.log('Router navigation Failed');

  // Notify the user
  alert('Could not move to this route');
  
}

Now, whenever, there is an error while navigating a route, the user will get a prompt:

Detect Navigational Errors in Angular

Conclusion

To detect route change in Angular, we can subscribe to the NavigationStart and NavigationEnd events of the Angular router.

The NavigationStart event is fired as soon as the navigation process starts whereas the NavigationEnd event is fired when the user successfully navigates to the route.

You can also detect the navigational errors inside the NavigationError event of the router.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.