Angular 2 router event listener

new router

constructor(router:Router) {
  router.events.subscribe(event:Event => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

old

Inject the Router and subscribe to route change events

import {Router} from 'angular2/router';

class MyComponent {
  constructor(router:Router) {
    router.subscribe(...)
  }
}

NOTE

For the new router, don’t forget to import NavigationStart from router module

import { Router, NavigationStart } from '@angular/router';

because if you don’t import it instanceof will not work and an error NavigationStart is not defined will rise.

See also

Leave a Comment