angularcustom-scrolling

Browser style scroll behaviors in Angular 2


In React there's this thing called react-router-scroll: https://www.npmjs.com/package/react-router-scroll. It makes React app pages scroll like a normal site. So it scrolls to the top of each new page (route), and retains scroll position of past pages; when you click the back button it remembers where you were scrolled to on that page.

I'm looking for something like that in Angular2. I searched and didn't find anything like it. Should be out there somewhere.


Solution

  • I created a module which you can use like this :

    1-

    npm install scrollstore
    

    2- Go to your app.module ( where you import all your root modules ).

    import { ScrollStoreModule } from 'scrollStore';
    

    3- Add ScrollStoreModule to your app module

    @NgModule({
      bootstrap: [ AppComponent ],
      imports: [ 
        ScrollStoreModule, // put it here 
        BrowserModule,
        FormsModule,
        HttpModule 
        .. rest of your modules ....
      ]
    })
    
    export class AppModule { 
    ...
    

    That's it.

    What id does :

    Saves the route name before changing the route and when you go back if that saved route exist in sessionStorage , it will scroll to that position, otherwise it'll scroll to top of the page.

    Feel free to contribute.