2021-04-16 13:07:43 +02:00
|
|
|
import {NavigationEnd, Router} from '@angular/router';
|
|
|
|
import {Injectable} from '@angular/core';
|
|
|
|
import {Subscription} from 'rxjs';
|
2021-04-12 23:55:09 +02:00
|
|
|
|
|
|
|
@Injectable({
|
2021-04-16 13:07:43 +02:00
|
|
|
providedIn: 'root'
|
2021-04-12 23:55:09 +02:00
|
|
|
})
|
|
|
|
export class SmoothScroll {
|
|
|
|
private interval;
|
|
|
|
private readonly sub;
|
|
|
|
private lastRoute;
|
|
|
|
|
|
|
|
constructor(private router: Router) {
|
2021-04-23 18:25:52 +02:00
|
|
|
if(typeof window !== "undefined") {
|
|
|
|
this.sub = router.events.subscribe(event => {
|
|
|
|
if (event instanceof NavigationEnd) {
|
|
|
|
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) {
|
|
|
|
clearInterval(this.interval);
|
|
|
|
}
|
|
|
|
const yOffset = -100;
|
|
|
|
let position = 0;
|
|
|
|
let interval = setInterval(() => {
|
|
|
|
if (position !== element.getBoundingClientRect().top) {
|
|
|
|
position = element.getBoundingClientRect().top;
|
|
|
|
} else {
|
|
|
|
clearInterval(interval);
|
|
|
|
const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
|
|
|
|
window.scrollTo({top: y, behavior: 'smooth'});
|
|
|
|
}
|
|
|
|
}, 50);
|
|
|
|
}
|
|
|
|
if (i > 4 && this.interval) {
|
2021-04-12 23:55:09 +02:00
|
|
|
clearInterval(this.interval);
|
|
|
|
}
|
2021-04-23 18:25:52 +02:00
|
|
|
}, 100);
|
|
|
|
} else {
|
|
|
|
window.scrollTo({top: 0, behavior: 'smooth'});
|
|
|
|
}
|
|
|
|
this.lastRoute = this.getUrl(event.url);
|
2021-04-12 23:55:09 +02:00
|
|
|
}
|
2021-04-23 18:25:52 +02:00
|
|
|
});
|
|
|
|
}
|
2021-04-12 23:55:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private getUrl(url: string) {
|
|
|
|
return url.split('?')[0].split('#')[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
public clearSubscriptions() {
|
2021-04-16 13:07:43 +02:00
|
|
|
if (this.sub && this.sub instanceof Subscription) {
|
2021-04-12 23:55:09 +02:00
|
|
|
this.sub.unsubscribe();
|
|
|
|
}
|
2021-04-16 13:07:43 +02:00
|
|
|
if (this.interval) {
|
2021-04-12 23:55:09 +02:00
|
|
|
clearInterval(this.interval);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|