Project

General

Profile

1
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
    this.sub = router.events.subscribe(event => {
15
      if (event instanceof NavigationEnd) {
16
        if (this.interval) {
17
          clearInterval(this.interval);
18
        }
19
        const fragment = router.parseUrl(router.url).fragment;
20
        if (this.lastRoute !== this.getUrl(event.url)) {
21
          window.scrollTo({top: 0});
22
        }
23
        if (fragment) {
24
          let i = 0;
25
          this.interval = setInterval(() => {
26
            i++;
27
            const element = document.getElementById(fragment);
28
            if (element) {
29
              if (this.interval) {
30
                clearInterval(this.interval);
31
              }
32
              const yOffset = -100;
33
              let position = 0;
34
              let interval = setInterval(() => {
35
                if (position !== element.getBoundingClientRect().top) {
36
                  position = element.getBoundingClientRect().top;
37
                } else {
38
                  clearInterval(interval);
39
                  const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
40
                  window.scrollTo({top: y, behavior: 'smooth'});
41
                }
42
              }, 50);
43
            }
44
            if (i > 4 && this.interval) {
45
              clearInterval(this.interval);
46
            }
47
          }, 100);
48
        } else {
49
          window.scrollTo({top: 0, behavior: 'smooth'});
50
        }
51
        this.lastRoute = this.getUrl(event.url);
52
      }
53
    });
54
  }
55
  
56
  private getUrl(url: string) {
57
    return url.split('?')[0].split('#')[0];
58
  }
59
  
60
  public clearSubscriptions() {
61
    if (this.sub && this.sub instanceof Subscription) {
62
      this.sub.unsubscribe();
63
    }
64
    if (this.interval) {
65
      clearInterval(this.interval);
66
    }
67
  }
68
}
(21-21/22)