Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 317
Flyii Avatar asked Sep 12 '25 10:09

Flyii


1 Answers

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

like image 118
Gianluca Paris Avatar answered Sep 14 '25 00:09

Gianluca Paris