Categories
Uncategorized

Detecting Angular Router State Changes

Detecting Route state changes can be done by subscribing to the router and listening to the events being emitted. In the example below you will see all the router events that you can listen to in Angular.

demo.component.ts

import { Component } from '@angular/core';
import { Router, Event, NavigationStart, RoutesRecognized,
 RouteConfigLoadStart, RouteConfigLoadEnd, 
NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';

@Component({
    selector: 'demo-app',
    template: `<router-outlet></router-outlet>`
})
export class DemoAppComponent {
    constructor(private router: Router) {
        router.events.subscribe( (event: Event) => 
            if (event instanceof NavigationStart) {
                // Navigation started.
               console.log(event.url);
            }
           else if (event instanceof RoutesRecognized) { 
                // Router parses the URL and the routes are recognized.
            }
            else if (event instanceof RouteConfigLoadStart) {
               // Before the Router lazyloads a route configuration.
            }
            else if (event instanceof RouteConfigLoadEnd) { 
               // Route has been lazy loaded.
            }
             else if (event instanceof NavigationEnd) {
                // Navigation Ended Successfully.
                 console.log(event.url);
            }
            else if (event instanceof NavigationCancel) { 
                // Navigation is canceled as the Route-Guard returned false during navigation.
            }
            else if (event instanceof NavigationError) {
                // Navigation fails due to an unexpected error.
                  console.log(event.error);
            }
        });
    }
}