我正在使用此代码使我的应用程序在更改路线时滚动到顶部,一切正常,但是我想在更改查询参数时禁用此选项。我有棱角分明的材料标签,我的查询参数定义了在访问页面时应打开哪个标签,但是当我更改标签(也更改网址)时,它会自动滚动到顶部
我认为不可能做到这一点,但是也许你有答案
imports: [RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled'
})]
我想要仅更改选项卡时应用程序不会滚动到顶部
答案 0 :(得分:0)
查看属性scrollPositionRestoration
文档,发现以下内容:
您可以通过调整已启用的行为来实现自定义滚动恢复行为...
实施:
{
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled'
}
保留为:
imports: [RouterModule.forRoot(routes)]
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]);
}
});
}
}
这里是DEMO,用于重现您的问题。
这是DEMO的解决方案。
欢呼
答案 1 :(得分:0)
最后我找到了不滚动查询参数更改 here
的工作解决方案在过滤器旁边使用成对管道运算符的效果非常好,您可以将匹配过滤器的最后发出的值与当前值进行比较。
我自己的完整工作片段:
export class AppModule {
constructor( private router: Router, private viewportScroller: ViewportScroller ) {
this.router.events.pipe(
filter( ( e: Event ): e is Scroll => e instanceof Scroll ),
pairwise()
).subscribe( ( eventPair ) => {
const previousEvent = eventPair[ 0 ];
const event = eventPair[ 1 ];
if ( event.position ) {
// backward navigation
this.viewportScroller.scrollToPosition( event.position );
} else if ( event.anchor ) {
// anchor navigation
this.viewportScroller.scrollToAnchor( event.anchor );
} else {
// forward navigation
if ( (previousEvent.routerEvent.urlAfterRedirects.split( '?' )[ 0 ]) !== event.routerEvent.urlAfterRedirects.split( '?' )[ 0 ] ) {
// Routes don't match, this is actual forward navigation
// Default behavior: scroll to top
this.viewportScroller.scrollToPosition( [0, 0] );
}
}
} );
}
}