Reputation: 137
Hi I have this code in "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>
And I want the page to be scrolled to top when navigate from page to other. I have tried many.
first solution:
RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })
Second solution: In app.component.html
<router-outlet (activate)="onActivate($event)" ></router-outlet>
Then in app.component.ts
onActivate(event) {
window.scroll(0,0);
//or document.body.scrollTop = 0;
//or document.querySelector('body').scrollTo(0,0)
...
}
nothing worked, How can I do this? any help?
Upvotes: 4
Views: 13630
Reputation: 907
If at navigation don't want to scroll to the top and manually want to scroll by clicking on a button below things can be considered.
window.scroll(0,0);
//or document.body.scrollTop = 0;
//or document.querySelector('body').scrollTo(0,0)
this is not working as it is always at value 0, as angular creating its own viewport to render a different component inside
<router-outlet></router-outlet>
So better to target the immediate parent class or material tag
document.querySelector('your class name or material tag name').scrollTop = 0;
also, check if your parent element has the correct height style property
height:100%
Upvotes: 1
Reputation: 36299
You need to scroll the mat-sidenav-content
. The window itself is already at 0
when using this component, as the component uses a full viewport height with overflow to make it look like the page is scrolling. There is an existing github issue asking for a feature for this.
You can place this in your app component to fix the 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;
});
}
Upvotes: 11