Angular 2.0, how to detect route change on child component

Viewed 12048

How can I detect a route change on a child component?. This is what I have tried, but I only see the app component trace the route change. I want to be able to detect when the url change from e.g. #/meta/a/b/c to #/meta/a/b/c/d in the MetaDetailView component.

@RouteConfig([
    { path: '/', name: 'Home', redirectTo: ['Meta']},
    { path: '/meta/...', name: 'Meta', component: MetaMainComponent, useAsDefault: true},
    ...other routes...,
  ])    
export class AppComponent {
    constructor(private _router: Router) {
        _router.subscribe( (url) => console.log("app.url = " + url));
    }
}

@RouteConfig([
    { path: '/*other', name: 'Detail', component: MetaDetailViewComponent, useAsDefault: true},
])
export class MetaMainComponent {
    constructor(private _router: Router) {
        _router.subscribe( (url) => console.log("metamain.url = " + url));
        console.log("MetaMainComponent")
    }
}

export class MetaDetailViewComponent {
    constructor(private _router: Router) {
        _router.subscribe( (url) => console.log("metadetail.url = " + url));
        console.log("MetaDetailViewComponent")
    }
}

Thanks Jesper

3 Answers

RC3+ solution:

constructor(private router: Router) {
  router.events.subscribe(event => {
    if (event.constructor.name === 'NavigationStart') {
      console.log(event.url);
    }
  });
}

Alternatively, you can filter for the NavigationStart event using the filter pipe (RxJS 6+):

constructor(private router: Router) {
  router.events.pipe(
    filter(event => event instanceof NavigationStart),
  ).subscribe((event: NavigationStart) => {
    console.log(event.url);
  });
}
Related