防止在 Angular 中的单个 router.navigate 调用上滚动到顶部

Arr*_*rel 3 routes angular

我的 Angular 8 应用程序在导航到新页面时滚动到顶部。在一个特定页面上我有一个可排序的表格。导航到该页面时,它应该滚动到顶部,但是当单击表头单元格时,它应该使用排序更新查询参数,但滚动到顶部。

是否可以router.navigate(...)使用新的查询参数数据进行调用而不触发滚动到顶部,同时不禁用从路由本身滚动到顶部?

Dip*_*hah 5

您可以使用多个选项配置路由器模块。您应该能够使用scrollPositionRestoration选项保留滚动。

您可以像这样使用它:

RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'disabled' })
Run Code Online (Sandbox Code Playgroud)

话虽如此,此选项将保留所有页面的滚动位置。

如果您只想针对特定页面实现此目的,则可以选择在调用中使用navigationExtrasnavigate并在状态对象中以及AfterViewInit处理程序更新滚动位置时指定当前滚动位置。

假设您有一个包含表的容器,您可以使用ViewChild装饰器在组件文件中访问它。

// declare your container component
@ViewChild("container")
private container: ElementRef;

// after view init updated current scroll position
ngAfterViewInit() {
  const prevScrollPos = this.router.getCurrentNavigation()?.extras?.state?.scrollTop;
  if (prevScrollPos) {
    this.container.nativeElement.scrollTop = prevScrollPos;
  }
}

// specify scroll position on navigation
this.router.navigate(
  ['/login'],
  {
    state: { scrollTop: this.container.nativeElement.scrollTop }
  }
);
Run Code Online (Sandbox Code Playgroud)