Johnrednex
Johnrednex

Reputation: 305

Angular2 HostListener check URL change

I have a navbar component that is called in every pages of my website.
I want it to check when the URL change with a HostListener.

@HostListener('window:hashchange', ['$event'])
onHashChange(event) {
    this.checkCurrentURL();
}  

private checkCurrentURL(){
    console.log("loaction : "+window.location.pathname)
}

However it doesn't work. Any ideas ?

EDIT: SOLUTION

The solution I found is without HostListener, but it works.

constructor(private router : Router){
 router.events.subscribe((val) => {
  this.checkCurrentURL();
 });
}

Upvotes: 4

Views: 5363

Answers (2)

Anurag Ranjan
Anurag Ranjan

Reputation: 131

As Angular is Single page Application , so you can define a global variable window in one of the component and using window global variable we can track each and every route , ,

window.location.href

window.location.href will return the current Url , and thus we can check when the URL change

constructor(private router : Router){
 router.events.subscribe((val) => {
    console.log(window.location.href); 
 });
}

Upvotes: 1

Gaurav Joshi
Gaurav Joshi

Reputation: 482

You don't need a HostListener for this. Assuming you are developing a single page app, you wanna subscribe to route change event.

Upvotes: 3

Related Questions