Angular detect route change only when navigating to a different component

yanivps picture yanivps · Jan 21, 2019 · Viewed 9k times · Source

I am trying to do something upon route change (i.e scroll to top) only when navigating to a different component in my application but not when staying on the same component and just changing its view by a route to the same component with different query params

For example, If I am at /products?category=kitchen and I navigate to /products?category=bedroom I don't want the the operation (i.e scroll to top) to perform.

This is the code in my app.component.ts:

this.router.events.pipe(
  filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
  // Would like to check here if user navigates to different component
  if (window) window.scrollTo(0, 0);
});

Does anybody know how I can achieve that?

Answer

yanivps picture yanivps · Apr 29, 2020

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