Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 543
BBaysinger Avatar asked Apr 16 '26 01:04

BBaysinger


2 Answers

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.

like image 103
Milad Avatar answered Apr 17 '26 16:04

Milad


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;
      }
    });
  }
}
like image 44
adriancarriger Avatar answered Apr 17 '26 17:04

adriancarriger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!