Angular 2, How to display current route name? (router 3.0.0-beta.1)

10,665

If your routes are configured with your route name in the data property like this:

{
    path: 'somepath',
    component: SomeComponent,
    data: {
        name: 'My Route Name'
    }
}

In your app.component.ts you can import 'rxjs/add/operator/filter'; + import { ActivatedRoute, Router, NavigationEnd } from '@angular/router'; and do the following:

constructor(
  private route: ActivatedRoute,
  private router: Router
) { }

ngOnInit() {
  this.router.events
    .filter(event => event instanceof NavigationEnd)
    .subscribe(event => {
      let currentRoute = this.route.root;
      while (currentRoute.children[0] !== undefined) {
        currentRoute = currentRoute.children[0];
      }
      console.log(currentRoute.snapshot.data);
    })
}

This will listen for NavigationEnd events and then traverse down to the current route so that you can access the data of that route.

If you are on /somepage using the code above, it should print { name="My Route Name"} in your console.

Share:
10,665

Related videos on Youtube

Adrian Moisa
Author by

Adrian Moisa

Tech Lead, Project Manager, Founder at Qualia Vision

Updated on September 15, 2022

Comments

  • Adrian Moisa
    Adrian Moisa over 1 year

    I want to display the name of the route in the app.component.html template. I'm looking for a simple solution, something that can be written like this:

    {{router.currentRoute.name}}
    

    My current router config:

    export const routes: RouterConfig = [
        {
            path: '',
            redirectTo: '/catalog',
            pathMatch: 'full'
        },
        {
            path: 'catalog',
            name: 'Catalog', // Is this property deprecated?
            component: CatalogComponent
        },
        {
            path: 'summary',
            name: 'Summary',
            component: SummaryComponent
        }
    ];
    
  • Ivan
    Ivan over 7 years
    TypeError: this.router.events.filter is not a function
  • Bjorn 'Bjeaurn' S
    Bjorn 'Bjeaurn' S about 7 years
    Don't forget to import the filter function from rxjs