Revision 60884
Added by Konstantinos Triantafyllou about 3 years ago
smooth-scroll.ts | ||
---|---|---|
1 |
import {NavigationEnd, Router} from "@angular/router";
|
|
2 |
import {Injectable} from "@angular/core";
|
|
3 |
import {Subscription} from "rxjs";
|
|
1 |
import {NavigationEnd, Router} from '@angular/router';
|
|
2 |
import {Injectable} from '@angular/core';
|
|
3 |
import {Subscription} from 'rxjs';
|
|
4 | 4 |
|
5 | 5 |
@Injectable({ |
6 |
providedIn: "root"
|
|
6 |
providedIn: 'root'
|
|
7 | 7 |
}) |
8 | 8 |
export class SmoothScroll { |
9 | 9 |
private interval; |
... | ... | |
13 | 13 |
constructor(private router: Router) { |
14 | 14 |
this.sub = router.events.subscribe(event => { |
15 | 15 |
if (event instanceof NavigationEnd) { |
16 |
if(this.interval) { |
|
16 |
if (this.interval) {
|
|
17 | 17 |
clearInterval(this.interval); |
18 | 18 |
} |
19 | 19 |
const fragment = router.parseUrl(router.url).fragment; |
20 |
if (this.lastRoute !== this.getUrl(event.url)) { |
|
21 |
window.scrollTo({top: 0}); |
|
22 |
} |
|
20 | 23 |
if (fragment) { |
21 | 24 |
let i = 0; |
22 | 25 |
this.interval = setInterval(() => { |
23 | 26 |
i++; |
24 | 27 |
const element = document.getElementById(fragment); |
25 | 28 |
if (element) { |
26 |
if(this.interval) { |
|
29 |
if (this.interval) {
|
|
27 | 30 |
clearInterval(this.interval); |
28 | 31 |
} |
29 | 32 |
const yOffset = -100; |
30 | 33 |
let position = 0; |
31 | 34 |
let interval = setInterval(() => { |
32 |
if(position !== element.getBoundingClientRect().top) { |
|
35 |
if (position !== element.getBoundingClientRect().top) {
|
|
33 | 36 |
position = element.getBoundingClientRect().top; |
34 | 37 |
} else { |
35 | 38 |
clearInterval(interval); |
... | ... | |
38 | 41 |
} |
39 | 42 |
}, 50); |
40 | 43 |
} |
41 |
if(i > 4 && this.interval) { |
|
44 |
if (i > 4 && this.interval) {
|
|
42 | 45 |
clearInterval(this.interval); |
43 | 46 |
} |
44 | 47 |
}, 100); |
45 | 48 |
} else { |
46 |
if(this.lastRoute !== this.getUrl(event.url)) { |
|
47 |
window.scrollTo({top: 0}); |
|
48 |
} else { |
|
49 |
window.scrollTo({top: 0, behavior: "smooth"}); |
|
50 |
} |
|
49 |
window.scrollTo({top: 0, behavior: 'smooth'}); |
|
51 | 50 |
} |
52 | 51 |
this.lastRoute = this.getUrl(event.url); |
53 | 52 |
} |
... | ... | |
59 | 58 |
} |
60 | 59 |
|
61 | 60 |
public clearSubscriptions() { |
62 |
if(this.sub && this.sub instanceof Subscription) { |
|
61 |
if (this.sub && this.sub instanceof Subscription) {
|
|
63 | 62 |
this.sub.unsubscribe(); |
64 | 63 |
} |
65 |
if(this.interval) { |
|
64 |
if (this.interval) {
|
|
66 | 65 |
clearInterval(this.interval); |
67 | 66 |
} |
68 | 67 |
} |
Also available in: Unified diff
[Library | Trunk]: Fix scroll to top on route change