嗨,我在“Angular 11”中有这个代码:
app.component.html:
<div class="app-container">
<mat-toolbar >
</mat-toolbar>
<mat-sidenav-container >
<mat-sidenav role="navigation">
<mat-nav-list>
<!-- <a mat-list-item routerLink="." *ngFor="let nav of fillerNav">{{ nav }}</a> -->
</mat-sidenav>
<mat-sidenav-content role="main">
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
</div>
并且我希望在从页面导航到其他页面时将页面滚动到顶部。 我试过很多。
第一个解决方案:
RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })
第二种解决方案: 在 app.component.html
<router-outlet (activate)="onActivate($event)" ></router-outlet>
然后在 app.component.ts 中
onActivate(event) {
window.scroll(0,0);
//or document.body.scrollTop = 0;
//or document.querySelector('body').scrollTo(0,0)
...
}
没有任何效果,我该怎么做?有什么帮助吗?
答案 0 :(得分:2)
您需要滚动 mat-sidenav-content
。使用此组件时,窗口本身已经位于 0
处,因为该组件使用带有溢出的完整视口高度使其看起来像是在滚动页面。现有的 github issue 要求为此提供一项功能。
您可以将其放置在您的应用组件中以解决问题:
ngOnInit() {
this.router.events
// For newer versions or rxjs use a pipe on the filter:
// .pipe(filter(event => event instanceof NavigationEnd))
.filter(event => event instanceof NavigationEnd)
.subscribe(() => {
document.querySelector('.mat-sidenav-content').scrollTop = 0;
});
}