Arūnas Smaliukas
Arūnas Smaliukas

Reputation: 3321

Angular2 watch for route change

@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?

Upvotes: 26

Views: 29542

Answers (6)

danday74
danday74

Reputation: 57223

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)
  })
}

Upvotes: 0

Hinrich
Hinrich

Reputation: 14023

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.

Upvotes: 25

Alok Kamboj
Alok Kamboj

Reputation: 1027

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
 }
});

Upvotes: 4

Dimpu Aravind Buddha
Dimpu Aravind Buddha

Reputation: 9845

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');
});

Upvotes: 20

Do Nguyen Thanh
Do Nguyen Thanh

Reputation: 9

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;
  }
}

Upvotes: 0

Ulydev
Ulydev

Reputation: 343

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*/)
  }
}

Upvotes: 17

Related Questions