Reputation: 13
My problem is -- Consider there are two pages A and B. If I am on page A and scroll down the page and click some button to navigate to page B, the page B remains at the same scroll position that I have scrolled in page A. Instead of this I want the page B should load from the top no matter of how much I have scrolled on previous page.
app-routing.module.ts
const routes: Routes = [
{path:'', redirectTo:'home', pathMatch:'full'},
{path:'home', component: HomeComponent},
{path:'about', component: AboutComponent},
{path:'product', component: ProductComponent},
{path:'contact', component: ContactComponent}
];
app.component.html
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
How to resolve this problem ?
And also I tried some solution like :
{scrollPositionRestoration: 'enabled'}
(activate)="onActivate($event)
window.scrollTo(0,0)
All these things I tried is scrolling all over the top(page B) from that scrolled position on previous page(page A). Any other solution for this or I am missing anything ?
Upvotes: 0
Views: 2078
Reputation: 99
Here's how I did it, in the container AppComponent
:
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
let x = document.getElementsByClassName('mat-drawer-content');
if (x.length > 0) x[0].scrollTo(0, 0);
});
If you're using the mat-drawer
from Angular material this will work. If you're using another div that scrolls replace it with that.
Upvotes: 0
Reputation: 409
Try this: In your component B HTML, wrap your page in <main>
. Then, in your component B,
component-b.ts
export class ComponentB implements AfterViewInit {
@ViewChild('main') main: ElementRef;
ngAfterViewInit() {
this.main.nativeElement.scrollTop = 0;
}
}
This should scroll the page to the top after the page is loaded.
Upvotes: 0