Angular2 watch for route change
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');
});
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.
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*/)
}
}
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
}
});