Angular和重定向时滚动到顶部

3

在Angular中是否有类似于在检测到URL更改时滚动到网站顶部的功能?如果没有,如何在TypeScript和HTML文件中进行重定向(或导航)时滚动到顶部?

编辑:

我在其中一个主题中看到:

ngOnInit() {
  this.router.events.subscribe((evt) => {
    if (!(evt instanceof NavigationEnd)) {
      return;
    }
    document.body.scrollTop = 0;
  });
}

但在我的应用中,它无法正常工作。我认为这行代码存在问题。

document.body.scrollTop = 0;

因为当我将它与console.log('tmp')交换时,它会检测到路由的更改。

2个回答

4

router-outlet有一个名为activate的方法,当组件被加载时会调用该方法。您可以利用这个方法,在您的app-component中滚动到顶部。因此,在您的app-component中:

<router-outlet (activate)="onActivate($event)"></router-outlet>

TS:

onActivate(event: Event) {
  window.scrollTo(0, 0);
}

太好了,很高兴听到这个消息 :) - AT82

2
现在最新的更新中,您可以在根路由中启用此选项,如下所示 -
@NgModule({
  imports: [
      RouterModule.forRoot(routes, {
         scrollPositionRestoration: 'top'
      })
  ]
})
export class AppRoutingModule {}

更多详情请参见此处 -


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接