26
@RouteConfig([
    {path: '/about', name: 'About', component: About, useAsDefault: true},
    {path: '/test', name: 'Test', component: Test}
])

export class MyApp {
    router: Router;
    location: Location;
    isCollapsed: boolean = true;

    // ON ROUTE CHANGE {
        this.isCollapsed = true;
    // }

    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}

I need change variable value on every route change, how to watch for this event in Angular 2.x?

SnareChops
  • 13,175
  • 9
  • 69
  • 91
Arūnas Smaliukas
  • 3,231
  • 6
  • 27
  • 46
  • For the new router (=> RC.3) see http://stackoverflow.com/questions/37137455/angular-2-typescript-error-when-using-subscribe-function-on-new-router-rc-1/37137497#37137497 – Günter Zöchbauer Jul 18 '16 at 11:15

6 Answers6

25

In the final version of Angular (e.g. Angular 2/4), you can do this

this.router.events.subscribe((event) => {
    if(event.url) {
        console.log(event.url);
    }
});

Every time the route changes, events Observable has the info. Click here for docs.

Hinrich
  • 13,485
  • 7
  • 43
  • 66
  • 4
    This did the trick! Please note that the router element is an instance of Router: you should ```import {Router} from '@angular/router';``` and ```constructor(private router: Router) { }```. – adripanico Aug 16 '17 at 14:39
  • 7
    property url does not exist on type event. – tatsu Feb 16 '18 at 11:51
  • Can you answer for this question? sixtwo49843nine – Pappa S Jun 21 '20 at 13:36
  • There are now multiple event types in Angular, so you'll need to check the event type first. Then you can use the specific properties of each. E.g., `if (event instanceof NavigationEnd) { event.url...; }` See docs here for more types: https://angular.io/api/router/NavigationEnd – Tyler Forsythe May 19 '21 at 21:23
20

If you are using

"@angular/router": "3.0.0-alpha.7", 
"@angular/router-deprecated": "2.0.0-rc.2",

then

this.router.events.subscribe((event) => {
      console.log('route changed');
});
Gagantous
  • 432
  • 6
  • 29
  • 69
Dimpu Aravind Buddha
  • 9,505
  • 4
  • 17
  • 23
  • This is correct answer for current versions. Goli this was hard to find. +1 – Lucas Jan 04 '17 at 02:28
  • +1 Your answer is valid for the current version(s) of Angular2. `this.router.subscribe()` does not work anymore. Instead you need to subscribe to the `events` like stated by Dimpu! – bajro Jan 21 '17 at 15:04
17

Here's what I use in my app. You can subscribe to a Route instance to track changes.

class MyClass {
  constructor(private router: Router) {
    router.subscribe((val) => /*detect changes*/)
  }
}
Ulydev
  • 343
  • 4
  • 10
4

event is observable so you can subscribe to it, I have successfully tried it in angular5

this.router.events.subscribe((event) => {
console.log(event);
 if(event['url'] && event['url'] == '/') {
    console.log('Home page');
    //any other functionality you can do here
 }
});
Alok Kamboj
  • 1,017
  • 11
  • 12
0

If you want to catch the event when the route changes, and initialize some code like jQuery then use OnActive hook. For example:

import {Component} from 'angular2/core';
import {OnActivate,ComponentInstruction} from "angular2/router";
declare var $:any;
declare var Foundation:any;
@Component({
templateUrl :'/app/templates/home.html'
})
export class HomeComponent implements OnActivate{

  routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction)
  {

    new Foundation.Orbit($("#es-slide-show"), {});
    return true;
  }
}
4castle
  • 32,613
  • 11
  • 69
  • 106
0

This is the best way to do it:

import { NavigationEnd, Router, RouterEvent } from '@angular/router'

constructor(private router: Router) {}

ngOnInit(): void {
  this.router.events.pipe(
    filter((evt: RouterEvent) => evt instanceof NavigationEnd)
  ).subscribe((evt: RouterEvent) => {
    // with the above filter, both the following will always log the same url
    console.log(evt.url)
    console.log(this.router.url)
  })
}
danday74
  • 52,471
  • 49
  • 232
  • 283