问题描述
我正在使用此代码使我的应用程序在更改路线时滚动到顶部,一切正常,但我想在更改查询参数时禁用此选项.我有角度材质选项卡,我的查询参数定义了访问页面时应该打开哪个选项卡,但是当我更改选项卡(也更改 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:
您可以通过调整启用的行为来实现自定义滚动恢复行为...
实施:
- 删除添加的代码:
{
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled'
}
保持原样:
imports: [RouterModule.forRoot(routes)]
- 在
app.module.ts
中添加以下代码:
- 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!