Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
 });
}
like image 206
Johnrednex Avatar asked Oct 16 '25 03:10

Johnrednex


1 Answers

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

like image 182
Gaurav Joshi Avatar answered Oct 18 '25 20:10

Gaurav Joshi