Question: angular2 scroll top on router change
當我們在第一個路由滑動到底部當我們點擊導航跳轉到另一個路由時頁面沒有回到頂部而是保持上一個路由的滾動位置,基本的解決辦法有兩種。
第一種解決方法是在組建的ngOnIinit()中進行調換路由后的重置
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'my-app',
template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0)
});
}
}
第二種解決方法是在import中對路由進行注入的時候設置scrollPositionRestoration
參數(angular6之后)。
RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})