angular RouteReuseStrategy滚动位置保持

angular RouteReuseStrategy scroll position keep

angular RouteReuseStrategy滚动位置错误。

当我从其他页面返回到列表页面时,滚动条回到顶部

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

}

如果您使用的不是 window 滚动而是 div 自动溢出,您应该订阅路由器事件并保存位置。

这里有一个例子(我用Angular Material Sidenav作为容器,但是你可以换成通用的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
    }
  })
}

非常感谢。我重建了路由器插座来解决这个问题,但它会占用大量内存。推荐参考 ionic, ion-router

我指的是离子,

添加了一个名为 <active-outlet> 的新 <router-outlet>

不会破坏组件,组件会被隐藏。

并添加新的生命周期函数

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