要在Angular 9中实现每次路由变化时滚动至顶部,可以使用@angular/router模块的NavigationEnd事件和window.scrollTo方法。以下是一个示例解决方法:
app.component.ts文件中导入所需的模块和服务:import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
AppComponent类中订阅NavigationEnd事件,并在路由变化时调用滚动方法:export class AppComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
window.scrollTo(0, 0);
}
});
}
}
app.component.html中添加组件的内容。以上代码将在每次路由变化完成时触发NavigationEnd事件,并调用window.scrollTo(0, 0)方法将页面滚动至顶部。