当路线发生变化时,我试图在我的 Angular 2 网站上滚动到我的页面顶部,我尝试了以下操作,但没有任何反应,当我将路线从一个页面更改为另一个页面时,页面滚动到它在第一页的位置:
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)
});
}
}
我做错了什么?
最佳答案
当新组件加载到 <router-outlet>
中时,路由器将发出一个事件这样您就可以将事件附加到它。
因此在您的组件中使用 <router-outlet>
使用:
<router-outlet (activate)="scrollTop($event)">
然后在您放置 <router-outlet>
的同一组件中添加以下方法:
scrollTop(event) {
window.scroll(0,0);
}
关于javascript - Angular 2滚动到顶部的路线更改不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53182560/