Angular detect route change only when navigating to a different component
I want to share how I solved this just in case someone will encounter somthing similar in the future:
private componentBeforeNavigation = null;
private setScrollToTopOnNavigation() {
// Scroll to top only when navigating to a different component
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
let currentRoute = this.route;
while (currentRoute.firstChild) currentRoute = currentRoute.firstChild;
if (this.componentBeforeNavigation !== currentRoute.component) {
if (window) window.scrollTo(0, 0);
}
this.componentBeforeNavigation = currentRoute.component;
});
}
What this code is doing is using a private property for the component called componentBeforeNavigation
which is initially null
and every time the Navigation event is fired, the code in the subscribe
check if the place I'm navigating now is the same as the last navigation. If yes, it means it is a navigation to the same component and I don't perform my special action (in this case scroll to top of the window) and if no, it means it is a navigation to a new component.
One important thing is to store the new component that I'm navigating to in the property componentBeforeNavigation
so it is always updated with the last navigation
You can subscribe to the ActivatedRoute
paramMap to do your stuff:
this.activatedRoute.paramMap.subscribe(paramMap => {
this.router.navigate('your child route here');
});
and make sure the category view is a child route of products
.
Also in place of products view in html template add a routing placeholder where the child view will be placed:
<router-outlet></router-outlet>
You can read more about nested routing here: