use*_*331 18 javascript jquery 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)
});
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Mac*_*c_W 13
当新组件加载到路由器时,路由器将发出事件,<router-outlet>因此您可以向其附加事件.
所以在你的组件中<router-outlet>使用:
<router-outlet (activate)="scrollTop($event)">
然后在放置的同一组件中<router-outlet>添加以下方法:
scrollTop(event) {
window.scroll(0,0);
}
Run Code Online (Sandbox Code Playgroud)