Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular RouteReuseStrategy scroll position keep

angular RouteReuseStrategy scroll position error.

When I returned to the list page from another page, the scroll bar went back to the top

import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';

export class SystemRouteReuseStrategy implements RouteReuseStrategy {

  handlers: {[key: string]: DetachedRouteHandle} = {};

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    if (route.data.reuse) {
      return true;
    }
    return false;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    this.handlers[route.routeConfig.path] = handle;
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    return this.handlers[route.routeConfig.path]; 
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig;
  }

}

like image 378
HelloWorld Avatar asked Oct 27 '22 03:10

HelloWorld


1 Answers

If you are not using the window scrolling but a div with auto overflow, you should subscribe to the router events and save the position.

Here is an example (I'm using Angular Material Sidenav as a container, but you can change to a general div)

lastPosition: number
lastRoute: string
@ViewChild('grid') grid: MatDrawerContent // change to ElementRef or other type

constructor(private router: Router) {}

ngOnInit() {
  this.router.events.pipe(
    filter((events) => events instanceof NavigationStart || events instanceof NavigationEnd)
  ).subscribe(event => {
    if (event instanceof NavigationStart && event.url !== this.lastRoute) {
      this.lastRoute = this.router.url
      this.lastPosition = this.grid.measureScrollOffset('top') // get the scrollTop property
      // this.lastPosition = this.grid.nativeElement.scrollTop
    } 
    else if (event instanceof NavigationEnd && event.url === this.lastRoute) {
      this.grid.scrollTo({ top: this.lastPosition }) // set scrollTop to last position
      // this.grid.nativeElement.firstChild.scrollTop  = this.lastPosition
    }
  })
}
like image 77
ST7 Avatar answered Jan 02 '23 19:01

ST7