Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
];
like image 891
Adrian Moisa Avatar asked Aug 04 '16 09:08

Adrian Moisa


People also ask

How can you get the current state of a route in Angular?

Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.

What would you use in Angular 2 to define route?

We use the router-outlet directive, an Angular 2 Routing directive that displays the active route (like ng-view ).

What does ActivatedRoute do in Angular?

ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.

What is RouterLink?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes. Let's explore how to use RouterLink , Router.


1 Answers

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.

like image 139
Mark Leong Avatar answered Oct 15 '22 21:10

Mark Leong