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

user11962606 picture user11962606 · Dec 16, 2019 · Viewed 9.6k times · Source

I want to change a certain heading according to the current url in Angular. So component.ts looks like this:

import {Router} from '@angular/router';
//code
public name: string
constructor(
    public router: Router
  ) {}
getName()
{
if(this.router.url === "/some_list")
{this.name = "List"}
else if(this.router.url === "/detail")
{this.name = "Detail"}
}

And then

<a>{{this.name}}</a>

The existing answers, like How to detect a route change in Angular? could not tell me how to do something after a change in routing (change = true or false). So how can I run this function whenever the url changes, so that the heading is according to the current view?

Answer

Surjeet Bhadauriya picture Surjeet Bhadauriya · Dec 16, 2019

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