skip to Main Content

The Angular Router has the ability to configure the router to restore scrolling and the linked documentation provides an example of how to do it when loading data.

How do we just configure the standalone router to restore the router outlet scroll to the top?

As can be seen in this demo, without any configuration, if two views have content that can be scrolled to the bottom, if one does scroll to the bottom, the viewport will stay that way when navigating across components.

https://stackblitz.com/edit/angular-adcsej?file=src%2Fmain.ts

2

Answers


  1. Chosen as BEST ANSWER

    When using the standalone Angular bootstrapApplication function to provide the router with the provideRouter function, the router can be configured like this to always scroll back to the top.

    const scrollConfig: InMemoryScrollingOptions = {
      scrollPositionRestoration: 'top',
      anchorScrolling: 'enabled',
    };
    
    const inMemoryScrollingFeature: InMemoryScrollingFeature =
      withInMemoryScrolling(scrollConfig);
    bootstrapApplication(App, {
      providers: [provideRouter(routes, inMemoryScrollingFeature)],
    });
    
    

    Here's a Demo: https://stackblitz.com/edit/angular-quflkz?file=src%2Fmain.ts

    The relevant documentation.

    This demo shows what happens if scroll restoration is not used.

    https://stackblitz.com/edit/angular-adcsej?file=src%2Fmain.ts


  2. If I understand correctly, you want the page to always scroll up when routing? Why such behavior? After all, when rerouting, a new page/component always starts at the top.

    But one way is to set in AppModule / AppRoutingModule the scrollPositionRestoration as it is in the documentation posted by you.

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

    ‘top’- Sets the scroll position to x = 0, y = 0 on all navigation.

    Or you can create your own logic for scrolling for example via service and inject it to the module.

    import { Injectable } from '@angular/core';
    import { Router, NavigationEnd } from '@angular/router';
    import { filter } from 'rxjs/operators';
    
    @Injectable()
    export class ScrollToTopService {
      constructor(router: Router) {
        router.events.pipe(
          filter(event => event instanceof NavigationEnd)
        ).subscribe(() => {
          window.scrollTo(0, 0);
        });
      }
    }
    

    So instead of scrollPositionRestoration you would add inside module

    providers: [ScrollToTopService]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search