Last active
April 9, 2019 08:53
-
-
Save yahasa/d9f7c0ac62dd269d4ec94bd7116f42a5 to your computer and use it in GitHub Desktop.
Keep scroll positions for routes in Angular app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, this functionality is not working for me (In Angular 5.2.6)