Flyii
Flyii

Reputation: 1155

Angular how to detect if child/nested route returned to parent

I have a component which can be reached by the path:

/parent

In that component I have a child/nested routes which can be reached by the path:

/parent/child1
/parent/child2

In the components in the child/nested routes i have a button that routes back to the parent component with

  this.router.navigate(['parent']);

What i want to happen is to call a method in the parent component only once whenever the child/nested routes navigate back to the parent.

But the problem i am facing right now is that i am not sure how i can detect that. I have tried it with lifecycle hooks but none of those really helped me. Routing back to the parent, the ngOnInit wont get called and the other lifecycles hooks are called more than one time.

EDIT: I know that i could handle this by having a StateService which the child components call before routing back and the parent would subscibe to the state but that sounds like a bad solution to me

Upvotes: 4

Views: 4127

Answers (1)

Gianluca Paris
Gianluca Paris

Reputation: 1429

In your component, you can use

import { Router } from '@angular/router'

constructor(private router: Router){}

this.router.events.subscribe(route => {
   //here you have different event types
   //NavigationStart tells you the route you come from
   //NavigationEnd tells you the route you are reaching
})

So you can check if you are going back to the parent easily. Make a console.log(route) so you can see the returned object

Upvotes: 2

Related Questions