Angular 17组件中如何仅修改查询参数时禁止页面滚动?
问题描述
我在app.config.ts中配置了页面导航时自动滚动到顶部:
// app.config.ts const scrollConfig: InMemoryScrollingOptions = { scrollPositionRestoration: 'top', }; const inMemoryScrollingFeature: InMemoryScrollingFeature = withInMemoryScrolling(scrollConfig); export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes, inMemoryScrollingFeature), ], };
但在通过app.component.ts修改查询参数时,页面也会自动滚动到顶部,这不是我想要的效果:
// app.component.ts addQueryParam(key: string, value: string) { this.router.navigate([], { relativeTo: this.route, queryParams: { [key]: value }, queryParamsHandling: 'merge', }); } deleteQueryParam(key: string) { this.router.navigate([], { relativeTo: this.route, queryParams: { ...this.route.snapshot.queryParams, [key]: null }, queryParamsHandling: 'merge', }); }
请问如何在仅修改查询参数时禁止页面滚动?
解决方案
在调用router.navigate时,添加scrollPositionRestoration: 'disabled'配置项,覆盖全局滚动设置,即可避免修改查询参数时页面滚动到顶部:
修改后的代码:
// app.component.ts addQueryParam(key: string, value: string) { this.router.navigate([], { relativeTo: this.route, queryParams: { [key]: value }, queryParamsHandling: 'merge', scrollPositionRestoration: 'disabled' // 新增配置 }); } deleteQueryParam(key: string) { this.router.navigate([], { relativeTo: this.route, queryParams: { ...this.route.snapshot.queryParams, [key]: null }, queryParamsHandling: 'merge', scrollPositionRestoration: 'disabled' // 新增配置 }); }
原理说明:
Angular路由的scrollPositionRestoration支持在单次导航中单独配置,优先级高于全局设置。将其设为'disabled'会禁用本次导航的滚动恢复逻辑,仅保留全局配置在路由路径变化(真正页面跳转)时生效,精准区分“修改查询参数”和“页面跳转”两种场景。
内容的提问来源于stack exchange,提问作者Asmaa Mahmoud
相关产品推荐
相关产品推荐

