Angular Get Current Path After Navigation

Here we will discuss how to get current page URL in Angular component dynamically after navigation is completed. For that we need to setup a subscription using the Router class of Angular as shown below:

Get URL using the Router class and Subscription

After navigating to a new page, we need to update the Path. For getting the route pathname dynamically, we need to a Router subscription which will be emitting the event after the Navigation is completed.

Step 1) Import Router and NavigationEnd Class

Step 2) Add the constructor and inject Router

Step 3) Create a subscription to get NavigationEnd event

 

The final component class will have the following code to have a subscription

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  activePath: string = '';

  constructor(private router: Router) {

    this.router.events.subscribe((event) => {

      if (event instanceof NavigationEnd) {

        this.activePath = event.url;
        console.log({ event });
        console.log(this.router.url);
        console.log(window.location.pathname);
      }
      
    });
  }
}

The event object inside the subscription returns the URL to reflect the route pathname.

Interestingly you can also use the router.url or window.location.pathname as well to get the same result.

HTML template will have the links to switch routes and print active pathname:

<a routerLink="/dashboard">Dashboard</a> |
<a routerLink="/profile">Profile</a> |
<a routerLink="/settings">Settings</a> 

Active Path : {{activePath}}

<router-outlet></router-outlet>

The output of above implementation will look like this:

 

 

 

 

 

 

Leave a Comment

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

istanbul escortHacklinkartvin escortGiresun escortEscortporno izleizmir escortsincan escortistanbul escortizmir escortGaziantep escortşişli escortkartal escortbodrum escortAntalya escortMarmaris escortpornoankara escortistanbul escortizmir escortizmir escorthttps://escortcity.net/Ankara çilingironwin girişHacklink satın alçankaya escortAyvalık Escortkütahya escortgümüşhane escortAksaray escortaydın escortkayseri escortçankaya escortkızılay escortkeçiören escorthepabeteryaman escortKiralık Bahis Siteleribonus veren sitelerKiralık Bahis Siteleri
Diş eti ağrısıankara kocaeli nakliyatgüvenlik bariyerisakarya evden eve nakliyatgaziantep evden eve nakliyatnargilehttps://www.orneknakliyat.comseowordpress en iyi seo eklentileripuro satın alBeard Transplantizmir saç ekimiistanbul evden eve nakliyatimplantbebekeskişehir inşaat şirketleriantika eşya alanlarantika eşya alanlarGülüş Tasarımıantalya haberCar Accident Lawyerpgcdpmsagaziantep boşanma avukatıAntika alan yerlermaltepe antika eşya alanlar