-
Notifications
You must be signed in to change notification settings - Fork 448
/
scroll-active.directive.ts
61 lines (48 loc) · 1.62 KB
/
scroll-active.directive.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
import { AfterViewInit, Directive, ElementRef, Input, OnChanges, Renderer2 } from '@angular/core';
@Directive({
selector: '[sqxScrollActive]'
})
export class ScrollActiveDirective implements AfterViewInit, OnChanges {
@Input('sqxScrollActive')
public isActive = false;
@Input('sqxScrollContainer')
public container: HTMLElement;
constructor(
private readonly element: ElementRef,
private readonly renderer: Renderer2
) {
}
public ngAfterViewInit() {
this.check();
}
public ngOnChanges() {
this.check();
}
private check() {
if (this.isActive && this.container) {
this.scrollInView(this.container, this.element.nativeElement);
}
}
private scrollInView(parent: HTMLElement, target: HTMLElement) {
const parentRect = parent.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const body = document.body;
const offset = (targetRect.top + body.scrollTop) - (parentRect.top + body.scrollTop);
const scroll = parent.scrollTop;
if (offset < 0) {
this.renderer.setProperty(parent, 'scrollTop', scroll + offset);
} else {
const targetHeight = targetRect.height;
const parentHeight = parentRect.height;
if ((offset + targetHeight) > parentHeight) {
this.renderer.setProperty(parent, 'scrollTop', scroll + offset - parentHeight + targetHeight);
}
}
}
}