3

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Subscribe to route changes

You can subscribe to route events, and when the user navigates to a new route you can set document.body.scrollTop to 0. Make sure to include it in a root level component that will be loaded for any requested route.

Component

import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private router: Router) { }
  ngOnInit() {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        document.body.scrollTop = 0;
      }
    });
  }
}

1 Comment

I have something like this in place now. It works for new pages, but doesn't address remembering page positions for navigating back through history.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.