Angular 7 在子路线更改时禁用滚动到顶部

Sas*_*mar 2 angular angular7 angular7-router

我有两个选项可以滚动到页面顶部。第一的,

router.events.subscribe((evt) => {
    if (evt instanceof NavigationEnd) {
        window.scroll({
            top: 0,
            left: 0,
            behavior: 'smooth'
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

Angular 6 提供的第二个选项是,

RouterModule.forRoot(AppRoutes, { 
      scrollPositionRestoration: "enabled"
})
Run Code Online (Sandbox Code Playgroud)

当我更改路线时,页面将移动到顶部,并且按预期工作。我在页面的几乎底部有使用子路线的选项卡部分。当子路由被触发时,页面将移动到页面顶部,而不是保留在选项卡部分。

所以我需要禁用子路线上的滚动到顶部功能。有什么办法可以做到吗?

任何帮助/想法表示赞赏。

ter*_*rtz 6

如果您在滚动到顶部之前检查当前路线是选项卡部分的子路线之一,则可能会起作用。

//for scalability, define routes you don't want to scroll to top in a string array

const noScrollRoutes: string[] = ['route/tabSubRoute1', 'route/tabSubRoute2'];

router.events.subscribe((evt) => {
    if (evt instanceof NavigationEnd) {
        if(noScrollRoutes.find(this.router.url) == undefined){ //if can't a route in predefined array, scroll to top
           window.scroll({
               top: 0,
               left: 0,
               behavior: 'smooth'
           });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

另外,您可能需要删除scrollPositionRestoration: "enabled"并将其保持禁用状态。