0

In my Angular 6 app when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me the next page but it doesn't scroll to the top of the page. As a result, if the first page(PARENT) is lengthy and 2nd page(CHILD) has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if user scroll to the top of the page.

I tried with adding "scrollPositionRestoration" for child like,

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

This gives me error as :

(property) scrollPositionRestoration: string
Expected 1 arguments, but got 2.

How to Resolve this ? Any Idea to Scroll Top of the Page for Angular Child Component ?

ABHILASHA K.M
  • 146
  • 1
  • 4
  • 16
  • I got the solution for this issue. Kindly check on: https://stackoverflow.com/questions/48048299/angular-5-scroll-to-top-on-every-route-click – ABHILASHA K.M May 26 '20 at 08:40

4 Answers4

3

I assume you have added the scrollPositionRestoration option in your AppRoutingModule like this:

...

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

And if you have the following code in your stylesheet:

html,
body {
  height: 100%;
}

Your scroll to the top will break! ¡#$%&*+@#!

You can remove this property or perhaps change your code to:

html {
  min-height: 100%;
  display: flex;
}
body {
  min-height: 100%;
  flex: 1;
}

Attention! Be carefull changing your stylesheet because it can break other things...

Rafael Neto
  • 1,036
  • 10
  • 16
2

If all fails, then create some empty HTML element (eg: div) at the top (or desired scroll to location) with id="top" on template (or parent template):

<div id="top"></div>

And in component:

ngAfterViewInit() {
    // Hack: Scrolls to top of Page after page view initialized
    let top = document.getElementById('top');
    if (top !== null) {
      top.scrollIntoView();
      top = null;
    }
  }
ABHILASHA K.M
  • 146
  • 1
  • 4
  • 16
0

Use ViewportScroller

ts:

import { ViewportScroller } from '@angular/common';

constructor(private viewportScroller: ViewportScroller){
}

public scrollTo(anchor: string): void { // for calling to anchors
    this.viewportScroller.scrollToAnchor(anchor);
}

ngOnInit(){
    this.viewportScroller.scrollToPosition([0, 0]);
}

html:

<div id="srollingEl"></div>
<button (click)="scrollTo('srollingEl')"></button>
Emir Mamashov
  • 1,108
  • 9
  • 14
0
html { 
 height: 100%;    
}
body {
 height: 100%;
 overflow: auto;
}