Search code examples
angularscrollcomponentsparent-child

scrollPositionRestoration adding for Angular Child Route


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 ?


Solution

  • 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;
        }
      }