关于导航到新路线的滚动问题
Scroll Issue on Navigating to new Route
当我从现有路线导航到新路线时,我的新页面不会在顶部打开。
我已经尝试了很多选择。
这是我找到的解决方案之一,但它对我不起作用。
export class AppComponent implements OnInit {
constructor(private router: Router, private changeDetect: ChangeDetectorRef) {
}
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
console.log(evt)
window.scrollTo(0, 0);
this.changeDetect.detectChanges();
});
}
}
有什么建议吗?
您可以使用 App.component.ts 中的这个选项修复它:
router.events.pairwise().subscribe((event: [NavigationEnd, NavigationEnd]) => {
if (event[0] instanceof NavigationEnd) {
window.scroll(0, 0);
}
});
选项 2:
Angular 6.1 有
的支持
RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})
我尝试了对我有用的不同解决方案
export class AppComponent implements OnInit {
constructor(private router: Router, private changeDetect: ChangeDetectorRef) {
}
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
// Change height:100% into auto
$('body').css('height', 'auto');
// Successfully scroll back to top
$('body').scrollTop(0);
// Remove javascript added styles
$('body').css('height', '');
this.changeDetect.detectChanges();
});
}
}
当我从现有路线导航到新路线时,我的新页面不会在顶部打开。
我已经尝试了很多选择。 这是我找到的解决方案之一,但它对我不起作用。
export class AppComponent implements OnInit {
constructor(private router: Router, private changeDetect: ChangeDetectorRef) {
}
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
console.log(evt)
window.scrollTo(0, 0);
this.changeDetect.detectChanges();
});
}
}
有什么建议吗?
您可以使用 App.component.ts 中的这个选项修复它:
router.events.pairwise().subscribe((event: [NavigationEnd, NavigationEnd]) => {
if (event[0] instanceof NavigationEnd) {
window.scroll(0, 0);
}
});
选项 2:
Angular 6.1 有
的支持RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})
我尝试了对我有用的不同解决方案
export class AppComponent implements OnInit {
constructor(private router: Router, private changeDetect: ChangeDetectorRef) {
}
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
// Change height:100% into auto
$('body').css('height', 'auto');
// Successfully scroll back to top
$('body').scrollTop(0);
// Remove javascript added styles
$('body').css('height', '');
this.changeDetect.detectChanges();
});
}
}