1

I have a root component and want to display route title inside special section in it.
I can detect which route is active in every component.
However, I don`t know how to do it inside root component.

This code shows title fine in ChildComponent1 :

route:ActivatedRoute
ngOnInit() {

        this.route.data.subscribe(
            data => console.log(data)
        )

    }

How can I detect what is current route`s title and display it inside the root component?

export const routes: Routes = [

  {path: '', component: Component1, canActivate: [NonAuthGuard]},

  {
    path: 'root', component: rootcomponent, canActivate: [AuthGuard], children: [
    {
      path: 'Child1',
      component: ChildComponent1,
      data: {
        title: 'Child1'
      },
      canActivate: [AuthGuard],
      canDeactivate: [CanDeactivateGuard]
    },
     {
      path: 'Child2',
      component: ChildComponent2,
      data: {
        title: 'Child2'
      },
      canActivate: [AuthGuard],
      canDeactivate: [CanDeactivateGuard]
    },
]}
boraseoksoon
  • 2,164
  • 1
  • 20
  • 25
norweny
  • 313
  • 1
  • 3
  • 15
  • UPD: Found the answer here http://stackoverflow.com/questions/38644314/changing-the-page-title-using-the-angular-2-new-router – norweny Oct 11 '16 at 09:44

1 Answers1

0

You could inject Router in your root component and then subscribe its events. Example:

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

You should check if your event is instance of NavigationStart or NavigationEnd, because your event will fire several times.

Kamil Myśliwiec
  • 8,548
  • 2
  • 34
  • 33
  • And how should I access route`s data title? Event object contains only id and urls. {id: 1, url: "/url/url1", urlAfterRedirects: "/url/url1"} – norweny Oct 11 '16 at 09:05
  • what do you mean by route's data title? – micronyks Oct 11 '16 at 09:06
  • I provided my array of routes(routes constant) which describes how to navigate inside application. Each route has data field with title attribute. – norweny Oct 11 '16 at 09:12