[Library | Trunk]: Fix scroll to top on route change

git-svn-id: https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/uoa-services-library/trunk/ng-openaire-library/src/app@60884 d315682c-612b-4755-9ff5-7f18f6832af3
This commit is contained in:
k.triantafyllou 2021-04-16 11:07:43 +00:00
parent 78f6d85d45
commit e9259ae1ed
1 changed files with 14 additions and 15 deletions

View File

@ -1,9 +1,9 @@
import {NavigationEnd, Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {Subscription} from "rxjs";
import {NavigationEnd, Router} from '@angular/router';
import {Injectable} from '@angular/core';
import {Subscription} from 'rxjs';
@Injectable({
providedIn: "root"
providedIn: 'root'
})
export class SmoothScroll {
private interval;
@ -13,23 +13,26 @@ export class SmoothScroll {
constructor(private router: Router) {
this.sub = router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
if(this.interval) {
if (this.interval) {
clearInterval(this.interval);
}
const fragment = router.parseUrl(router.url).fragment;
if (this.lastRoute !== this.getUrl(event.url)) {
window.scrollTo({top: 0});
}
if (fragment) {
let i = 0;
this.interval = setInterval(() => {
i++;
const element = document.getElementById(fragment);
if (element) {
if(this.interval) {
if (this.interval) {
clearInterval(this.interval);
}
const yOffset = -100;
let position = 0;
let interval = setInterval(() => {
if(position !== element.getBoundingClientRect().top) {
if (position !== element.getBoundingClientRect().top) {
position = element.getBoundingClientRect().top;
} else {
clearInterval(interval);
@ -38,16 +41,12 @@ export class SmoothScroll {
}
}, 50);
}
if(i > 4 && this.interval) {
if (i > 4 && this.interval) {
clearInterval(this.interval);
}
}, 100);
} else {
if(this.lastRoute !== this.getUrl(event.url)) {
window.scrollTo({top: 0});
} else {
window.scrollTo({top: 0, behavior: "smooth"});
}
window.scrollTo({top: 0, behavior: 'smooth'});
}
this.lastRoute = this.getUrl(event.url);
}
@ -59,10 +58,10 @@ export class SmoothScroll {
}
public clearSubscriptions() {
if(this.sub && this.sub instanceof Subscription) {
if (this.sub && this.sub instanceof Subscription) {
this.sub.unsubscribe();
}
if(this.interval) {
if (this.interval) {
clearInterval(this.interval);
}
}