Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
Arūnas Smaliukas Avatar asked Dec 23 '15 22:12

Arūnas Smaliukas


People also ask

How does Angular determine routing change?

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.

Is ngOnDestroy called on route change?

ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.

Which event defined by the $route service is triggered after the route has changed?

The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/view change is done.


1 Answers

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.

like image 174
Hinrich Avatar answered Sep 30 '22 10:09

Hinrich