BBaysinger
BBaysinger

Reputation: 6847

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.

Upvotes: 3

Views: 589

Answers (2)

Milad
Milad

Reputation: 28590

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.

Upvotes: 3

adriancarriger
adriancarriger

Reputation: 3000

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

Upvotes: 2

Related Questions