2022-03-14 17:35:00 +01:00
|
|
|
import {ActivationStart, NavigationEnd, Router} from '@angular/router';
|
2021-04-16 13:07:43 +02:00
|
|
|
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;
|
2022-03-14 17:35:00 +01:00
|
|
|
private lastComponent;
|
|
|
|
private currentComponent: any;
|
2021-04-12 23:55:09 +02:00
|
|
|
|
|
|
|
constructor(private router: Router) {
|
2022-03-14 17:35:00 +01:00
|
|
|
if (typeof window !== "undefined") {
|
2021-04-23 18:25:52 +02:00
|
|
|
this.sub = router.events.subscribe(event => {
|
2022-03-14 17:35:00 +01:00
|
|
|
if (event instanceof ActivationStart) {
|
|
|
|
this.currentComponent = event.snapshot.component;
|
|
|
|
} else if (event instanceof NavigationEnd) {
|
2021-04-23 18:25:52 +02:00
|
|
|
if (this.interval) {
|
|
|
|
clearInterval(this.interval);
|
|
|
|
}
|
|
|
|
const fragment = router.parseUrl(router.url).fragment;
|
2022-03-14 17:35:00 +01:00
|
|
|
if (this.lastComponent !== this.currentComponent) {
|
2021-04-23 18:25:52 +02:00
|
|
|
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'});
|
|
|
|
}
|
2022-03-14 17:35:00 +01:00
|
|
|
this.lastComponent = this.currentComponent;
|
2021-04-12 23:55:09 +02:00
|
|
|
}
|
2021-04-23 18:25:52 +02:00
|
|
|
});
|
|
|
|
}
|
2021-04-12 23:55:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|