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;
}
}
如果不是使用窗口滚动而是使用自动溢出的div,应该订阅路由器事件并保存位置。
下面是一个例子(我使用的是 角材侧影 作为一个容器,但你可以改成一个普通的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
}
})
}
非常感谢你。我已经重建了路由器-出口,解决了这个问题,但是会占用很多内存。推荐参考离子、离子路由器