Finding current URL with Angular 2.0 Routing

7 בJune 2016



For an application built with AngularJs 2.0 (rc1) I wanted to do one simple thing: To highlight
the current active navigation  bar item. However, I’ve had to do it with the new angular router,
the one that currently lacks documentation. So after a few searches online and digging through
the router object I’ve reached the solution I want to share.


Let’s start with the solution itself:

(Taken from the application’s entry component)

   1: constructor(private router:Router){

   2:       router.changes.subscribe(route =>{

   3:          this.currentRoute = this.getRoutePath(this.router.routeTree._root);

   4:       } );

   5:   }


   7:   getRoutePath(routeTreeNode:any){

   8:       if (!routeTreeNode) {

   9:           return '';

  10:       }


  12:       let result:string => segment.segment).join('/');


  14:       if (routeTreeNode.children.length){

  15:           result += '/' + this.getRoutePath(routeTreeNode.children[0]);

  16:       }


  18:       return result;

  19:   }


On the component’s constructor we subscribe to the router change,  then, on the event handler, we send the _root member of the router’s routeTree member.


Each node value has its urlSegment array which we need to build our url string from, using method.

For nested routing we will recursively call our method with the node’s children.


There may will be more appropriate way to do this (going through ‘_root’ member doesn’t feel right)
but  it works for now.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



  1. Pingback: (Update) Finding current URL with Angular 2.0 Routing | Ran Wahle's blog