Pardeep Jain
Pardeep Jain

Reputation: 86740

On route change view doesn't scroll to top in the new page in angular2

I have tried autoscroll="false" on the router-outlet but does't seem to work, is there any default method of angular2 for doing the same without using any third party library?

Upvotes: 4

Views: 12014

Answers (5)

Uland Nimblehoof
Uland Nimblehoof

Reputation: 1032

Just figured it out. It can be used as smooth scroller to precised ID or instant scroller in order to fix top position.

Component that route is driven to:

  ngAfterViewInit(): void {
    this.commonService.scrollTo('header', BEHAVIOR.auto)
  }

Service:

  scrollTo(element: string, behavior: BEHAVIOR): void {
    (document.getElementById(element) as HTMLElement).scrollIntoView({behavior: behavior, block: "start", inline: "nearest"});
  }

Enum:

export enum BEHAVIOR {
  smooth = 'smooth',
  auto = 'auto'
}

Upvotes: 0

Pardeep Jain
Pardeep Jain

Reputation: 86740

found answer here https://stackoverflow.com/a/39601987/5043867

we can subscribe to the route change event and scroll to the top with something in the lines of

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

Update -

In Angular v6+ there is a new method scrollPositionRestoration introduced. for more info read out here

Upvotes: 7

Pran R.V
Pran R.V

Reputation: 1158

Angular lately introduced a new feature, inside angular routing module make changes like below

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

Upvotes: 4

Hamzeen Hameem
Hamzeen Hameem

Reputation: 2560

Until Angular 6

here is a more neat way to do it:

this.router.events.subscribe((ev:any) => {
  if (ev instanceof NavigationEnd) {
    window.scrollTo(0, 0);
  }
});

From Angular 6.1

You could do this in your router configuration. This is likely to be the norm in future versions as suggested here.

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})

Upvotes: 8

micronyks
micronyks

Reputation: 55443

Yes, you can refer to fragments available in Angular2-router.

Upvotes: -3

Related Questions