在页面切换时,浏览器会记住上一个页面的滚动位置。
两种解决办法:
- 在页面切换前,将滚动位置恢复到顶部。
import { Router, NavigationStart } from '@angular/router';
// 组件中:
constructor(private router: Router) {}
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
window.scrollTo(0, 0);
}
});
- 在目标页面初始化时,将滚动位置恢复到顶部。
// 目标页:
ngOnInit() {
window.scrollTo(0, 0);
}