How to run a function when a route changes in angular?

Go this StackBlitz link

On every navigation start event of router you can get url and fire function. in you app.component.ts

ngOnInit(){
   this.router.events.subscribe(event =>{
      if (event instanceof NavigationStart){
         console.log(event.url)
         this.routerChangeMethod(event.url);
      }
   })
}

routerChangeMethod(url){
  this.title = url;
}

Yout app.component.html is..

{{title}}

<router-outlet></router-outlet>

As a good practice you should have one component per route.

RouterModule.forRoot([
    { path: 'products', component: DetailComponent },
    { path: 'shopping-cart', component: SomelistComponent }
])

If you keep to this practice, then you will have a separation of concern.

And then according to the route you just set header for your component.

You can read more about routing here.


You can subscribe to router event in the app.component.ts. It will fire every time you change the route.

  constructor(location: Location, router: Router) {
    // decide what to do when this event is triggered.
    router.events.subscribe(val => {
      if (location.path() != "/something") {
          // do something
      } else {
         // do something else
      }
    });
  }

Try this if it is calling multiple times

router.events.filter(event => event instanceof NavigationEnd).subscribe(val => { // here your code... })

Note: I have not tried this