angular 4 call component method when re-routing to it

2.3k Views Asked by At

I have a routing strategy that does not destroy the component when routing to another component. I would like to call a method of the component, when (re)routing to it.

Until now I've tried implementing the interfaces AfterContentChecked and AfteViewChecked with their respective methods ngAfterContentChecked and `ngAfterViewChecked. The only problem with implementing one of this interfaces is that the method is called multiple times when routing to the component and this is a performance problem for me.

While researching the web I haven't come across an interface which I could implement in order to obtain the desired behaviour.

Is the only possibility for solving this, verifying in the router which route/path was selected and in the case of the desired one, I call the method of the component?

3

There are 3 best solutions below

0
On BEST ANSWER

You can subscribe to the router's events, this will fire off an event each time your route changes. You can then get the active route of off this event and check if the route of the component you're currently in is equal to that route.

TIP: Filter on the events by using instanceof NavigationEnd

2
On

Whenever routing happens Component get created and ngOnInit function is called.

export class TestComponent implements OnInit{
  constructor(){
     //called first time before the ngOnInit()
  }

  ngOnInit(){
     //called after the constructor
  }
}

Other two options that we have are -

  1. Resover - resolve function

  2. Gaurds - canActive function

Resolver and Gaurd get executed whenever routing is changing.

0
On

You can basically add inject Router as a dependency and then subscribe to events on it. There is a list of events that Router exposes.

Since we only care about the NavigationEnd event, you can filter that out using the filter operator.

The event data has a url property that can be used to compare with the path that was attained after NavigationEnd

this.router.events
.pipe(
  filter(event => event instanceof NavigationEnd)
)
.subscribe((event: any) => {
  console.log('Got the Event URL as '. event.url);
})

Here's a Sample StackBlitz for your ref.