lampka w tubce
lampka w tubce

Reputation: 77

Angular and scroll to top when redirect

Is there in angular something like scrolling to top of website while url change is detected? If not, how to scroll to the top while there is redirect(or navigate) in typescript and also html files?

Edit:

I saw in one of topics:

ngOnInit() {
  this.router.events.subscribe((evt) => {
    if (!(evt instanceof NavigationEnd)) {
      return;
    }
    document.body.scrollTop = 0;
  });
}

but in my application it does not working. I think there's problem with line

document.body.scrollTop = 0;

, cause when I swap it with console.log('tmp') it detects route changing

Upvotes: 3

Views: 2878

Answers (2)

Pardeep Jain
Pardeep Jain

Reputation: 86740

Now with the latest update you can enable this option in root routing , like below -

@NgModule({
  imports: [
      RouterModule.forRoot(routes, {
         scrollPositionRestoration: 'top'
      })
  ]
})
export class AppRoutingModule {}

For more in details see here -

Upvotes: 2

AVJT82
AVJT82

Reputation: 73357

The router-outlet has a method activate, which is called when a component is loaded. You can utilize that and in your app-component scroll to top. So in your app-component:

<router-outlet (activate)="onActivate($event)"></router-outlet>

TS:

onActivate(event: Event) {
  window.scrollTo(0, 0);
}

Upvotes: 4

Related Questions