Search code examples
angularangular-router

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;
  }

}


Solution

  • I refer to ionic,

    A new <router-outlet> named <active-outlet> is added.

    It will not destroy the component, The component will be set to hidden.

    And add a new life cycle function

    ngOnChanges
    
    ngOnInit <- first entry create component 
    
    onReuse  <- second entry or router back reuse component 
    
    ngDoCheck
    
    ngAfterContentInit
    
    ngAfterContentChecked
    
    ngAfterViewInit
    
    ngAfterViewChecked
    
    onLeave   <- router level
    
    ngOnDestroy  <-  Manual destroy trigger