gpt4 book ai didi

Angular RouteReuseStrategy 滚动位置保持

转载 作者:行者123 更新时间:2023-12-03 19:19:51 28 4
gpt4 key购买 nike

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,您应该订阅路由器事件并保存位置。

这是一个示例(我使用 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
}
})
}

关于 Angular RouteReuseStrategy 滚动位置保持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59607867/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com