Skip to content

Instantly share code, notes, and snippets.

@yahasa
Last active April 9, 2019 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yahasa/d9f7c0ac62dd269d4ec94bd7116f42a5 to your computer and use it in GitHub Desktop.
Save yahasa/d9f7c0ac62dd269d4ec94bd7116f42a5 to your computer and use it in GitHub Desktop.
Keep scroll positions for routes in Angular app
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Subscription } from 'rxjs';
import 'rxjs/add/operator/pairwise';
@Component({
selector: 'app-root',
template: `/* ... your template */`,
styles: [`/* ... your styles */`]
})
export class AppComponent implements OnInit, OnDestroy {
private _routeScrollPositions: {[url: string] : number}[] = [];
private _subscriptions: Subscription[] = [];
constructor(private router: Router) {}
ngOnInit() {
this._subscriptions.push(
// save or restore scroll position on route change
this.router.events.pairwise().subscribe(([prevRouteEvent, currRouteEvent]) => {
if (prevRouteEvent instanceof NavigationEnd && currRouteEvent instanceof NavigationStart) {
this._routeScrollPositions[prevRouteEvent.urlAfterRedirects || prevRouteEvent.url] = window.pageYOffset;
}
if (currRouteEvent instanceof NavigationEnd) {
window.scrollTo(0, this._routeScrollPositions[currRouteEvent.urlAfterRedirects || currRouteEvent.url] || 0);
}
})
);
}
ngOnDestroy() {
this._subscriptions.forEach(subscription => subscription.unsubscribe());
}
}
@handkk
Copy link

handkk commented Apr 9, 2019

Hi, this functionality is not working for me (In Angular 5.2.6)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment