1

I am using a simple link to navigate to another page, with HashLocationStrategy :

<a href="/#/mypage">My Page</a></div>

After clicking the link above, mypage is being loaded, but since I scrolled down the previous page it is loaded in the middle of the page (same scroll position of previous page).

I do have a workaround, but why is this happening?

RJFalconer
  • 10,890
  • 5
  • 51
  • 66
Yuvals
  • 3,094
  • 5
  • 32
  • 60

4 Answers4

11

This is happening because there is no actual page refresh. There is no implementation yet on how to trigger this without using a workaround. I guess the main issue is that you can have multiple router-outlet in the same screen, and that in cases it should not scroll up.

Inside my AppComponent I use this workaround. You probably use the same:

constructor(private _router: Router) {}

ngOnInit() {
  this._router.events.subscribe((event: NavigationEnd) => {
    if(event instanceof NavigationEnd) {
      window.scrollTo(0, 0);
    }
  })
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • 1
    works like a charm, thank you – FloppyNotFound Nov 14 '17 at 14:57
  • I tried this but its not working for me as I have this block in my code, html,body { overflow-x: hidden; } Removing this will solve issue but I can't remove it as it will affect other components. any other solution? – khush Jul 26 '18 at 10:00
  • @khush the latest [angular (6.1.0)](https://github.com/angular/angular/blob/master/CHANGELOG.md#features) has support for restoring scroll – Poul Kruijt Jul 26 '18 at 10:07
  • but my now my project is on Angular v5 – khush Jul 26 '18 at 10:12
1

A workaround is to define on the target page:

@Component({
  ...
})
export class MyPageComponent {

   ngAfterViewInit() {
       window.scrollTo(0, 0);
   }
}
Yuvals
  • 3,094
  • 5
  • 32
  • 60
0

Its because Angular prevents the default action for a link click event, therefore the page isn't scrolling to the top.

As a workarround just subscribe to router.events and filter out the NavigationEnd event:

this.router.events.subscribe(event => {
  if(event instance of NavigationEnd) {
     ... scroll to top
  }
}
cyr_x
  • 13,987
  • 2
  • 32
  • 46
0

I do have a workaround, but why is this happening?

One of the reasons why it's happening, or better to say: it isn't happening, because Angular2 router can be used to navigate just inside a given outlet. You can have many named router outlets (or one somewhere lower in the page) and scrolling the page to top after navigating any of them would break the behavior. And as we can see adding the scroll functionality is not so hard to implement by yourself. Also worth to read: Named router outlets in Angular2

Daniel Kucal
  • 8,684
  • 6
  • 39
  • 64