Subscribing to Angular 2 Router Events

Executing code on state change in Angular 2 using NavigationStart

Posted on February 8, 2017

Tags:

Angular

The angular 2 Router provides an events observable which can be subscribed to which returns NavigationStart, RoutesRecognised and NavigationEnd event objects.

Here’s how to execute code on NavigationStart

1) Import Router and NavigationStart from @angular/router

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

2) Subscribe to the Router event within you constructor method and run your code

export class MyComponent {

	constructor ( private _router: Router ) {
		_router.events.subscribe ( event => {
			if( event instanceof NavigationStart ){
				// Add your code
			}
		} );
	}

}