Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular detect route change only when navigating to a different component

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?

like image 576
yanivps Avatar asked Jan 21 '19 20:01

yanivps


2 Answers

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

like image 161
yanivps Avatar answered Oct 20 '22 06:10

yanivps


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:

like image 23
nircraft Avatar answered Oct 20 '22 04:10

nircraft