How to get the current route or URL in Angular

Finding the the current route or URL in Angular is one of the common requirements in an App. There are many ways by which you can get a current Route or URL in Angular. You can use the router service, location service or window object to get the path. You can also listen to changes to URL using the router event or URL change event of the location service.

Using Router.url

Inject the Router and use the URL property.

Subscribe to Router Events

Subscribe to the NavigationStart Router Event and use the url property of the NavigationEvent. By subscribing to the event, you will always

Do not forget to unsubscribe, the subscription when the component is destroyed. Not doing so will lead to a memory leak as the subscription will keep running.

The route change even fires, only when the route changes. It won’t fire when the app starts for the first time.

Using Location Service

Import Location Service from the @angular/common. And use the Location.path() to get the current URL.

Listen to Location Change

Using Window

You can also use the window object to get the path. But remember that it works only if the app is using the browser. If you using Server Side Rending using Angular Universal then this will not work.

4 thoughts on “How to get the current route or URL in Angular”

  1. Great, Thanks for sharing this….
    I guess
    in
    Listen to Location Change—section
    below lines do not make any sense

    ngOnDestroy() {
    this.event$.unsubscribe()
    }

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top