752

The current docs only talk about getting route params, not the actual route segments.

For example, if i want to find the parent of current route, how is that possible?

2
  • 52
    window.location.pathname Oct 6, 2016 at 22:47
  • 6
    @dchacke the problem with window.location is that if in the future, they want to implement server-side rendering, they will face some difficulties since window does not exist on the Node.js server, but they need to use the Angular standard methods to access the route and they'll be fine both on server and browser. Mar 30, 2020 at 9:25

42 Answers 42

847

The new V3 router has a url property.

this.router.url === '/login'
18
  • 5
    I use this code and i am getting this url in string variable but when i try to print in console .log it is not printing this.fullUrl = this.router.url console.log(this.fullUrl); // not printing Oct 28, 2016 at 12:47
  • 67
    this is useless when you are navigating with Hash strategy, the url is always "/" Aug 1, 2017 at 17:27
  • 5
    @NinjaCoding I am using Hash strategy and I am getting just "/". How can i get route url with Hash ?
    – Murtuza
    Aug 3, 2018 at 3:00
  • 30
    @Murtuza here is a solution: this.router.events.filter((event: any) => event instanceof NavigationEnd).subscribe(event => { console.log('this is what your looking for ', event.url); }); . Make sure you import import { Router, NavigationEnd } from '@angular/router';
    – Gel
    Dec 14, 2018 at 5:38
  • 8
    @Murtuza pointed me in the right direction. However, not need to filter, just listen for NavigationEnd this.router.events.subscribe((event) => { event instanceof NavigationEnd ? console.log(event): null }) Nov 8, 2019 at 23:12
279

Angular RC4:

You can import Router from @angular/router

Then inject it:

constructor(private router: Router ) {

}

Then call it's URL parameter:

console.log(this.router.url); //  /routename
7
  • 5
    The extra clarity about how to import the router itself is very helpful. Could you clarify if it would be different if you were using a custom Router?
    – kbpontius
    Jan 25, 2017 at 0:44
  • 1
    That would certainly depend on the 'custom-ness' of the custom Router. (sorry this wasn't a particularly helpful comment -- if you have a specific question, I'd suggest making a new question and referencing this answer)
    – lowcrawler
    Jan 25, 2017 at 12:07
  • 112
    I used this solution, but I always get this " / ". Does anyone know why?
    – Marcio M.
    Jul 25, 2017 at 17:59
  • 4
    Angular Dependency Injection relies on the TypeScript sugar syntax, so when you declare private _router: Router in the constructor signature, a property _router is automatically created in the current class instance with the Router injected. This statement this.router = _router; is just an overhead to me, as you'd have two reference to the same object instance (in that case, the Router). Jan 30, 2018 at 17:21
  • 1
    @Marcio M. It might be because the router has not actually reached that state, even though the URL shows different. For example, if your look at the router.url in a guard service. location.path() as mentioned in the answers will give you the url, no matter what the router state is. Jan 31, 2018 at 10:58
74

Inject Location to your component and read location.path(); You need to add ROUTER_DIRECTIVES somewhere so Angular can resolve Location. You need to add import: [RouterModule] to the module.

Update

In the V3 (RC.3) router you can inject ActivatedRoute and access more details using its snapshot property.

constructor(private route:ActivatedRoute) {
  console.log(route);
}

or

constructor(private router:Router) {
  router.events.subscribe(...);
}

See also Angular 2 router event listener

9
  • 4
    that gives me the 'url' path. how do i find the 'route names' so i can pass them in an array on to the navigate method along with the (appended) name of child route i want to navigate to.
    – pdeva
    Jan 4, 2016 at 19:55
  • I see. I also don't find this satisfactory. I haven't tried it myself but maybe the MyTrackingService explained in stackoverflow.com/a/34548656/217408 would allow to access these values. Jan 4, 2016 at 19:59
  • 7
    @GunterZochbauer is there a way to get the requested route before it's activated? For example, if I want to store the requested route inside of a canActivate() method, so that I can redirect to a "login" page, and then redirect back to the original route after the user authenticates? Jul 9, 2016 at 20:52
  • 1
    Can't you do that with a canActivate guard? Jul 12, 2016 at 4:44
  • 1
    No idea why you think listening to these events could be expensive. Router event are quite infrequent and all this listening does is storing the callback in a list to be called when a router event happens. I'd say if you care about performance you're better off checking for unnecessary server requests and DOM re-render. Mar 16, 2020 at 11:30
73

Use this

import { Router, NavigationEnd } from '@angular/router';

constructor(private router: Router) {
    router.events.filter(event => event instanceof NavigationEnd)
        .subscribe(event => {
            console.log(event);
        });
}

And in main.ts import

import 'rxjs/add/operator/filter';

EDIT

Modern way

import {filter} from 'rxjs/operators';

router.events.pipe(
    filter(event => event instanceof NavigationEnd)
)
    .subscribe(event => {
        console.log(event);
    });
8
  • 24
    Is this really the recommended way to do something as simple as checking where the current URL is pointing? I'm not arguing against you on this one. However, I noticed that the routing thing is a source of many changes, updates, confusions etc. I was kind of expecting that ActivatedRoute would be used primarily for this, not Router. Am I missing the complexity of the issue, perhaps? May 10, 2018 at 10:45
  • 2
    No need for any at least here, the router exports the "RouterEvent" type that is extended by the other router events - angular.io/api/router/RouterEvent
    – chrismarx
    Nov 7, 2019 at 13:51
  • 1
    @chrismarx fixed
    – Vlad
    Nov 7, 2019 at 14:57
  • 1
    this works fine. but when i start the app, first time at that time no event is fired. this works when the route change
    – Sunil Garg
    Apr 22, 2020 at 7:14
  • 1
    @SunilGarg You could use the startsWith rxjs operator startWith(this.router.url), Oct 22, 2021 at 19:11
54

For those who are still looking for this. On Angular 2.x there are a few ways of doing it.

constructor(private router: Router, private activatedRoute: ActivatedRoute){

   // string path from root to current route. i.e /Root/CurrentRoute
   router.url 

    // just the fragment of the current route. i.e. CurrentRoute
   activatedRoute.url.value[0].path

    // same as above with urlSegment[]
   activatedRoute.url.subscribe((url: urlSegment[])=> console.log(url[0].path))

   // same as above
   activatedRoute.snapshot.url[0].path

   // the url fragment from the parent route i.e. Root
   // since the parent is an ActivatedRoute object, you can get the same using 
   activatedRoute.parent.url.value[0].path
}

References:

  1. https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html
  2. https://angular.io/docs/ts/latest/api/router/index/Router-class.html
  3. https://angular.io/docs/ts/latest/guide/router.html
0
44

for new router >= RC.3

Best and a simple way to do this is!

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  // to print only path eg:"/login"
}
2
  • How does this answer differ from lowcrawler's?
    – not2savvy
    May 24, 2017 at 11:33
  • 1
    @not2savvy had given one more way to find out the same through router event listener, which helped some of the people to find what they are looking for.
    – Rajath M S
    May 30, 2017 at 5:31
33
import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}
1
  • Hallelujah! :) Thanks!
    – Alexander
    Jun 15, 2021 at 20:10
31

To get the route segments:

import { ActivatedRoute, UrlSegment } from '@angular/router';

constructor( route: ActivatedRoute) {}

getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }
0
21

To reliably get the full current route you can use this

this.router.events.subscribe(
  (event: any) => {
    if (event instanceof NavigationEnd) {
      console.log('this.router.url', this.router.url);
    }
  }
);
1
  • This should be the correct answer, because if you change routes, this will catch it. Feb 21, 2021 at 10:45
19

An easier way if you can't access router.url (for instance if you used skipLocationChange) you can use the following :

import { Location } from '@angular/common';    
constructor(private readonly location: Location) {}
    
ngOnInit(): void {
  console.log(this.location.path());
}
16

You can try with

import { Router, ActivatedRoute} from '@angular/router';    

constructor(private router: Router, private activatedRoute:ActivatedRoute) {
console.log(activatedRoute.snapshot.url)  // array of states
console.log(activatedRoute.snapshot.url[0].path) }

Alternative ways

router.location.path();   this works only in browser console. 

window.location.pathname which gives the path name.

1
  • update: activatedRoute.snapshot.url is an Observable now and you have to subscripe to it.
    – Sadok Mtir
    Jun 20, 2017 at 12:30
14
import { Router, NavigationEnd } from "@angular/router";

constructor(private router: Router) {
  // Detect current route
  router.events.subscribe(val => {
    if (val instanceof NavigationEnd) {
      console.log(val.url);
    }
  });
}
1
  • It gave undefined value sometimes Oct 11, 2022 at 10:39
13

The native window object works fine as well

console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);

NOTE: DO NOT USE THIS IN SERVER SIDE RENDERING

1
  • 3
    Be careful if you are using server side rendering, this will break. May 3, 2018 at 2:18
8

to get current router in angular 8 just do this

import {ActivatedRoute} from '@angular/router';

then inject it in constructor like

constructor(private route: ActivatedRoute){}

if you want get current route then use this route.url

if you have multiply name route like /home/pages/list and you wanna access individual then you can access each of like this route.url.value[0].path

value[0] will give home, value[1] will give you pages and value[2] will give you list

1
  • url in ActivatedRoute is a BehaviorSubject, so one needs to use this.route.value.
    – Alexander
    Jun 23, 2022 at 10:07
7

I had the same problem using

this.router.url

I get the current route with query params. A workaround I did was using this instead:

this.router.url.split('?')[0]

Not a really nice solution, but helpful.

7

short version if you have Router imported then you can simply use some thing like

this.router.url === "/search"

else do the following

1) Import the router

import { Router } from '@angular/router';

2) Declare its entry in constructor

constructor(private router: Router) { }

3) Use its value in your function

yourFunction(){
    if(this.router.url === "/search"){
        //some logic
    }
}

@victor answer helped me, this is the same answer as him but with a little detail, as it might help someone

7

This applies if you are using it with an authguard

this.router.events.subscribe(event => {
        if(event instanceof NavigationStart){
            console.log('this is what your looking for ', event.url);  
         }
       } 
   );
6

With angular 2.2.1 (in an angular2-webpack-starter based project) works this:

export class AppComponent {
  subscription: Subscription;
  activeUrl: string;

  constructor(public appState: AppState,
              private router: Router) {
    console.log('[app] constructor AppComponent');
  }

  ngOnInit() {
    console.log('[app] ngOnInit');
    let _this = this;
    this.subscription = this.router.events.subscribe(function (s) {
      if (s instanceof NavigationEnd) {
        _this.activeUrl = s.urlAfterRedirects;
      }
    });
  }

  ngOnDestroy() {
    console.log('[app] ngOnDestroy: ');
    this.subscription.unsubscribe();
  }
}

In AppComponent's template you can use e.g. {{activeUrl}}.

This solution is inspired by RouterLinkActive's code.

1
  • this is a good answer b/c if you have a wild card route that redirects back to /home event.url is not enough to match the /home route it will actually show the route that does not exist. event.urlAfterRedirects will print the actual end route. ty. Apr 15, 2019 at 22:35
6

WAY 1: Using Angular: this.router.url

import { Component } from '@angular/core';

// Step 1: import the router 
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    //Step 2: Declare the same in the constructure.
    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        // Do comparision here.....
        ///////////////////////////
        console.log(this.router.url);
    }
}

WAY 2 Window.location as we do in the Javascript, If you don't want to use the router

this.href= window.location.href;
0
5

You can use in the .ts file

import { Route, Router, NavigationStart } from '@angular/router';

constructor(private router: Router) {}

this.router.events.subscribe(value => {
      if (value instanceof NavigationStart) {
        console.log(value) // your current route
      }
    });
5

simplest way

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  <---------- to get only path eg:"/signUp"
}
4

angular 2 rc2

router.urlTree.contains(router.createUrlTree(['/home']))
4

Here is what is working for me in Angular 2.3.1.

location: any;

constructor(private _router: Router) { 

      _router.events.subscribe((data:any) => { this.location = data.url; });

      console.warn(this.location);  // This should print only path e.g. "/home"
}

The data is an object and we need the url property contained in that object. So we capture that value in a variable and we can use that variable in our HTML page as well. For example, I want to show a div only when user is on Home page. In this case, my router url value will be /home. So I can write a div in the following way:

<div *ngIf="location == '/home'">
This is content for the home page.
</div>
4

You can use ActivatedRoute to get the current router

Original Answer (for RC version)

I found a solution on AngularJS Google Group and it's so easy!

ngOnInit() {
  this.router.subscribe((url) => console.log(url));
}

Here's the original answer

https://groups.google.com/d/msg/angular/wn1h0JPrF48/zl1sHJxbCQAJ

1
  • Has been changed as of rc.2, as url now is no longer the URL and a string, but a ComponentInstruction.
    – Martin C.
    Jul 1, 2016 at 10:59
4

I was facing the problem where I needed the URL path when the user is navigating through the app or accessing a URL (or refreshing on a specific URL) to display child components based on the URL.

More, I want an Observable that can be consumed in the template, so router.url was not an option. Nor router.events subscription because routing is fired before the component's template is initialized.

this.currentRouteURL$ = this.router.events.pipe(
     startWith(this.router),
     filter(
         (event) => event instanceof NavigationEnd || event instanceof Router
     ),
     map((event: NavigationEnd | Router) => event.url)
);

Hope it helps, good luck!

1
  • 2
    This is awesome.
    – codeepic
    May 9, 2019 at 15:28
4

router.events.subscribe(e => {
      if (e instanceof NavigationEnd) {
        this.currentUrl = e.url;
      }
    });

3

For your purposes you can use this.activatedRoute.pathFromRoot.

import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){

}

With the help of pathFromRoot you can get the list of parent urls and check if the needed part of the URL matches your condition.

For additional information please check this article http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ or install ng2-router-helper from npm

npm install ng2-router-helper
3

this is simple, in angular 2 you only need to import the Router library like this:

import { Router } from '@angular/router';

Then in the constructor of the component or service you must instantiate it like this:

constructor(private _router: Router) {}

Then in any part of the code, either in a function, method, construct, whatever:

      this._router.events
        .subscribe(
            (url:any) => {
                let _ruta = "";
                url.url.split("/").forEach(element => {
                    if(element!=="" && _ruta==="")
                        _ruta="/"+element;  
                });
                console.log("route: "+_ruta); //<<<---- Root path
                console.log("to URL:"+url.url); //<<<---- Destination URL                    
                console.log("from URL:"+this._router.url);//<<<---- Current URL
            }); 
0
3

To find the parent of the current route, you can obtain the UrlTree from the router, using relative routes:

var tree:UrlTree = router.createUrlTree(['../'], {relativeTo: route});

Then to get the segments of the primary outlet:

tree.root.children[PRIMARY_OUTLET].segments;
3

As of now, I'm getting my path as follows -

this.router.url.subscribe(value => {
    // you may print value to see the actual object
    // console.log(JSON.stringify(value));
    this.isPreview = value[0].path === 'preview';
})

Where, router is an instance of ActivatedRoute

Not the answer you're looking for? Browse other questions tagged or ask your own question.