Newer
Older
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import {
ComponentRef, Directive, EmbeddedViewRef, Input, OnDestroy, ViewContainerRef
} from '@angular/core';
import { TooltipComponent } from 'common/components/tooltip/tooltip.component';
import { TooltipPosition } from 'common/models/elements/element';
@Directive()
export abstract class BaseTooltipDirective implements OnDestroy {
@Input() tooltipText = '';
@Input() tooltipPosition: TooltipPosition = 'below';
tooltipElement!: HTMLElement;
hideDelay: number = 3000;
private componentRef: ComponentRef<TooltipComponent> | null = null;
constructor(protected viewContainerRef: ViewContainerRef) {}
showTooltip(): void {
if (!this.componentRef) {
this.createComponent();
this.setTooltipComponentProperties();
}
}
hideTooltipWithDelay(): void {
setTimeout(() => this.hideTooltip(), this.hideDelay);
}
hideTooltip(): void {
this.destroyComponent();
}
private createComponent(): void {
this.componentRef = this.viewContainerRef.createComponent(TooltipComponent);
const domElem =
(this.componentRef.hostView as EmbeddedViewRef<TooltipComponent>)
.rootNodes[0] as HTMLElement;
document.body.appendChild(domElem);
}
private setTooltipComponentProperties(): void {
this.setTooltipText();
this.setTooltipPosition();
}
private setTooltipText(): void {
if (this.componentRef) {
this.componentRef.instance.tooltipText = this.tooltipText;
}
}
private setTooltipPosition(): void {
if (this.componentRef) {
this.componentRef.instance.tooltipPosition = this.tooltipPosition;
const {
left, right, top, bottom
} = this.tooltipElement.getBoundingClientRect();
switch (this.tooltipPosition) {
case 'right': {
this.componentRef.instance.left = Math.round(right);
this.componentRef.instance.top = Math.round(top + (bottom - top) / 2);
break;
}
case 'left': {
this.componentRef.instance.left = Math.round(left);
this.componentRef.instance.top = Math.round(top + (bottom - top) / 2);
break;
}
case 'above': {
this.componentRef.instance.left = Math.round((right - left) / 2 + left);
this.componentRef.instance.top = Math.round(top);
break;
}
default: { // below
this.componentRef.instance.left = Math.round((right - left) / 2 + left);
this.componentRef.instance.top = Math.round(bottom);
break;
}
}
}
}
private destroyComponent(): void {
if (this.componentRef) {
this.componentRef.destroy();
this.componentRef = null;
}
}
ngOnDestroy(): void {
this.destroyComponent();
}
}