Categories
Angular Answers

How to detect a route change in Angular?

Spread the love

Sometimes, we want to detect a route change in Angular.

In this article, we’ll look at how to detect a route change in Angular.

How to detect a route change in Angular?

To detect a route change in Angular, we use router.events.subscribe.

For instance, we write

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

@Component({
  selector: "app-root",
  template: `<router-outlet></router-outlet>`,
})
export class AppComponent {
  constructor(private router: Router) {
    this.router.events.subscribe((event: Event) => {
      if (event instanceof NavigationStart) {
        // ...
      }

      if (event instanceof NavigationEnd) {
        // ...
      }

      if (event instanceof NavigationError) {
        // ...
        console.log(event.error);
      }
    });
  }
}

to call this.router.events.subscribe with a callback that listens for navigation events.

In it, we check if event is an instance of NavigationStart, which is emitted when navigation starts.

Also, we check if event is an instance of NavigationEnd, which is emitted when navigation ends.

And we check if event is an instance of NavigationError, which is emitted when there’s an error during navigation.

Conclusion

To detect a route change in Angular, we use router.events.subscribe.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *