I have the following route configuration:
{
path: 'foo',
component: 'fooComponent'
},
{
path: 'bar',
children: [
{
path: ':barId',
component: barComponent,
children: [
{
path: ':bazId',
component: bazComponent,
outlet: 'baz'
}
]
}
]
}
I'm currently on bazComponent
. The current URL is http://localhost:4200/bar/barId/(baz:bazId)
Is there any way to detect when the user has left bazComponent
?
I need to execute some code when the user navigates from bazComponent
to any other route that does not contain the baz
outlet.
EDIT: The code I have to execute is within function inside the component that can't be moved.
You should probably create an Angular Route Guard and use the CanDeactivate
to execute the code that you want to be executed on leaving that route, this is preferable if you need to apply to multiple routes.
After you mentioned that it needs to call a function within that component and it's just for the single component you should use OnDestroy.
class AppComponent implements OnDestroy {
ngOnDestroy() {
// Call to function/method here.
}
}
Check out the Lifecycle Hooks.