fix scroll location not saved on page change
This commit is contained in:
1 parent
c5883cf6f5
commit
b852d40bca
1 file changed
+34
-3
@@ -1,5 +1,5 @@
|
||||
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
|
||||
import { NavigationEnd, Router } from '@angular/router';
|
||||
import { NavigationEnd, NavigationStart, Router } from '@angular/router';
|
||||
import { filter } from 'rxjs';
|
||||
|
||||
import PerfectScrollbar from 'perfect-scrollbar';
|
||||
@@ -14,16 +14,47 @@ export class AppComponent implements AfterViewInit {
|
||||
|
||||
@ViewChild('scrollContainer', { static: true }) scrollContainer!: ElementRef;
|
||||
private ps!: PerfectScrollbar;
|
||||
private scrollPositions = new Map<string, number>();
|
||||
private isBackNavigation = '';
|
||||
|
||||
constructor(private router: Router) {}
|
||||
|
||||
ngAfterViewInit() {
|
||||
this.ps = new PerfectScrollbar(this.scrollContainer.nativeElement);
|
||||
|
||||
// this.router.events
|
||||
// .pipe(filter(event => event instanceof NavigationEnd))
|
||||
// .subscribe(() => {
|
||||
// this.scrollToTop();
|
||||
// });
|
||||
|
||||
// Save scroll position before navigation
|
||||
this.router.events
|
||||
.pipe(filter(event => event instanceof NavigationEnd))
|
||||
.pipe(filter((event) => event instanceof NavigationStart))
|
||||
.subscribe((e) => {
|
||||
if (e instanceof NavigationStart) {
|
||||
this.isBackNavigation = e.navigationTrigger?.toString()!;
|
||||
const currentUrl = this.router.url;
|
||||
const scrollTop = this.scrollContainer.nativeElement.scrollTop;
|
||||
this.scrollPositions.set(currentUrl, scrollTop); // Save current scroll position
|
||||
}
|
||||
});
|
||||
|
||||
// Restore scroll position after navigation
|
||||
this.router.events
|
||||
.pipe(filter((event) => event instanceof NavigationEnd))
|
||||
.subscribe(() => {
|
||||
this.scrollToTop();
|
||||
// ? case of backward / forward
|
||||
if (this.isBackNavigation == 'popstate') {
|
||||
const currentUrl = this.router.url;
|
||||
const savedScrollTop = this.scrollPositions.get(currentUrl) || 0;
|
||||
this.scrollContainer.nativeElement.scrollTop = savedScrollTop; // Restore scroll position
|
||||
this.ps.update();
|
||||
} else if (this.isBackNavigation == 'imperative') {
|
||||
// ? case of visiting page
|
||||
this.scrollContainer.nativeElement.scrollTop = 0; // Scroll top
|
||||
this.ps.update();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user