Project

General

Profile

1 61381 k.triantaf
import {NavigationEnd, Router} from '@angular/router';
2
import {Injectable} from '@angular/core';
3
import {Subscription} from 'rxjs';
4
5
@Injectable({
6
  providedIn: 'root'
7
})
8
export class SmoothScroll {
9
  private interval;
10
  private readonly sub;
11
  private lastRoute;
12
13
  constructor(private router: Router) {
14
    if(typeof window !== "undefined") {
15
      this.sub = router.events.subscribe(event => {
16
        if (event instanceof NavigationEnd) {
17
          if (this.interval) {
18
            clearInterval(this.interval);
19
          }
20
          const fragment = router.parseUrl(router.url).fragment;
21
          if (this.lastRoute !== this.getUrl(event.url)) {
22
            window.scrollTo({top: 0});
23
          }
24
          if (fragment) {
25
            let i = 0;
26
            this.interval = setInterval(() => {
27
              i++;
28
              const element = document.getElementById(fragment);
29
              if (element) {
30
                if (this.interval) {
31
                  clearInterval(this.interval);
32
                }
33
                const yOffset = -100;
34
                let position = 0;
35
                let interval = setInterval(() => {
36
                  if (position !== element.getBoundingClientRect().top) {
37
                    position = element.getBoundingClientRect().top;
38
                  } else {
39
                    clearInterval(interval);
40
                    const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
41
                    window.scrollTo({top: y, behavior: 'smooth'});
42
                  }
43
                }, 50);
44
              }
45
              if (i > 4 && this.interval) {
46
                clearInterval(this.interval);
47
              }
48
            }, 100);
49
          } else {
50
            window.scrollTo({top: 0, behavior: 'smooth'});
51
          }
52
          this.lastRoute = this.getUrl(event.url);
53
        }
54
      });
55
    }
56
  }
57
58
  private getUrl(url: string) {
59
    return url.split('?')[0].split('#')[0];
60
  }
61
62
  public clearSubscriptions() {
63
    if (this.sub && this.sub instanceof Subscription) {
64
      this.sub.unsubscribe();
65
    }
66
    if (this.interval) {
67
      clearInterval(this.interval);
68
    }
69
  }
70
}