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?

1

6 Answers 6

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.

4
  • 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, 2017 at 14:39
  • 7
    property url does not exist on type event.
    – tatsu
    Feb 16, 2018 at 11:51
  • Can you answer for this question? sixtwo49843nine
    – Pappa S
    Jun 21, 2020 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: angular.io/api/router/NavigationEnd May 19, 2021 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');
});
2
  • This is correct answer for current versions. Goli this was hard to find. +1
    – Lucas
    Jan 4, 2017 at 2: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, 2017 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*/)
  }
}
5
  • Sorry, down-voted this before you changed the answer for Angular2, this is correct
    – Zyzle
    Dec 23, 2015 at 22:53
  • 1
    Thanks! Works perfect. Dec 23, 2015 at 23:03
  • 2
    @ulydev will you please provide plnkr or working code for this routerChange detection i cannot get you How to use your code. Dec 24, 2015 at 6:08
  • 1
    router.subscribe does not fire with angular beta.2 any idea ?
    – harikrish
    Feb 25, 2016 at 18:22
  • Try this.router.changes.subscribe Sep 14, 2016 at 7:43
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
 }
});
1
  • 3
    valid answer on angular 6
    – Ryan Arief
    Nov 5, 2018 at 5:46
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;
  }
}
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)
  })
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.