@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?
Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.
ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.
The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/view change is done.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With