How to detect a route change in Angular?
How to detect a route change in Angular?
To detect a route change in Angular, you can subscribe to the router events observable provided by the Angular Router. This observable emits navigation-related events, including start and end of navigation, route recognition, and errors. Here's a step-by-step guide on how to implement route change detection:
Import the Router and Event Types: First, you need to import Router and the event types you want to listen for from @angular/router. The event types include NavigationStart, NavigationEnd, NavigationCancel, NavigationError, and others.
import { Router, Event, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';
Subscribe to Router Events: Inject the Router into your component's constructor and subscribe to its events observable. You can then filter the events based on their instance type to detect specific navigation events.
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
// Navigation is starting
console.log('Route change detected');
} else if (event instanceof NavigationEnd) {
// Navigation End
console.log(event);
} else if (event instanceof NavigationCancel) {
// Navigation Cancel
console.log('NavigationCancel ', event.url);
} else if (event instanceof NavigationError) {
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.