更改查询参数 - 页面滚动顶部,Angular [英] Changing query params - page scrolls top, Angular

查看:27
本文介绍了更改查询参数 - 页面滚动顶部,Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码使我的应用程序在更改路线时滚动到顶部,一切正常,但我想在更改查询参数时禁用此选项.我有角度材质选项卡,我的查询参数定义了访问页面时应该打开哪个选项卡,但是当我更改选项卡(也更改 url)时,它会自动滚动顶部

I'm using this code to make my app scroll to top when changing routes, everything works fine, but i would like to disable this option when changing query params. I have angular material tabs and my query params define which tab should be opened when visiting page, but when i change tab (also changes url) it automatically scrolls top

我认为简单的方法是不可能的,但也许你有答案

I think it is impossible to do it easy way, but maybe you have answer

  imports: [RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled',
    anchorScrolling: 'enabled'
  })]

我希望仅更改选项卡时应用程序不会滚动顶部

I want when changing only tabs the app wouldn't scroll top

推荐答案

看属性 scrollPositionRestoration 文档,发现这个:

Looking at the property scrollPositionRestoration documentation, found this:

您可以通过调整启用的行为来实现自定义滚动恢复行为...

You can implement custom scroll restoration behavior by adapting the enabled behavior...

实施:

  1. 删除添加的代码:

{
  scrollPositionRestoration: 'enabled',
  anchorScrolling: 'enabled'
}

保持原样:

imports: [RouterModule.forRoot(routes)]

  1. app.module.ts中添加以下代码:
  1. Add the following code to app.module.ts:

import { Event, Scroll, Router } from '@angular/router';
import { ViewportScroller } from '@angular/common';

export class AppModule {
  constructor(router: Router, viewportScroller: ViewportScroller) {
    router.events.pipe(
      filter((e: Event): e is Scroll => e instanceof Scroll)
    ).subscribe(e => {
      // here you'll have your own logic, this is just an example.
      if (!router.url.includes('hello')) {
        viewportScroller.scrollToPosition([0, 0]);
      }
    });

  }
}

这是一个用于重现您的问题的演示.

Here is a DEMO for reproducing your issue.

这是一个 DEMO 用这个解决方案解决它.

And this is a DEMO resolving it with this solution.

干杯

这篇关于更改查询参数 - 页面滚动顶部,Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆