red-ui/.tmp/ar-tooltip/ar-tooltip.directive.ts
2020-11-25 10:55:36 +02:00

128 lines
3.2 KiB
TypeScript

import {
ComponentRef,
Directive,
ElementRef,
HostListener,
Input,
OnChanges,
OnDestroy,
OnInit,
SimpleChanges
} from '@angular/core';
import {Overlay, OverlayPositionBuilder, OverlayRef} from '@angular/cdk/overlay';
import {ComponentPortal} from '@angular/cdk/portal';
import {TooltipContentComponent} from './tooltip-content/tooltip-content.component';
import {TooltipModel} from './tooltip-content/tooltip.model';
import {ArOverlayPosition, Placement} from '../../common/model/ar-overlay-position';
import {NavigationStart, Router} from '@angular/router';
@Directive({
selector: '[upExtTooltip]',
exportAs: 'upExtTooltip'
})
export class ArTooltipDirective implements OnInit, OnChanges, OnDestroy {
@Input() upExtTooltip: string | TooltipModel;
@Input() placement: Placement = 'top';
private overlayRef: OverlayRef;
private tooltipRef: ComponentRef<TooltipContentComponent>;
private _enable = true;
protected test:string;
constructor(protected overlayPositionBuilder: OverlayPositionBuilder,
protected router: Router,
protected elementRef: ElementRef,
protected overlay: Overlay) {
}
ngOnInit(): void {
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
this.destroyOverlay();
}
});
}
ngOnChanges(changes: SimpleChanges): void {
if (this.tooltipRef && this.upExtTooltip) {
this.tooltipRef.instance.tooltip = this.upExtTooltip instanceof TooltipModel ? this.upExtTooltip : new TooltipModel(null, this.upExtTooltip);
}
}
ngOnDestroy(): void {
this.destroyOverlay();
}
@HostListener('mouseover', ['$event'])
show($event) {
if (this._enable) {
$event.stopPropagation();
$event.preventDefault();
this.open();
}
}
open(model?: TooltipModel) {
if (!this.overlayRef) {
this.createOverlay();
}
if (model) {
this.upExtTooltip = model;
}
if (this.upExtTooltip) {
this.overlayRef.detach();
const tooltipPortal = new ComponentPortal(TooltipContentComponent);
this.tooltipRef = this.overlayRef.attach(tooltipPortal);
this.tooltipRef.instance.tooltip = this.upExtTooltip instanceof TooltipModel ? this.upExtTooltip : new TooltipModel(null, this.upExtTooltip);
}
}
close() {
this.destroyOverlay();
}
@HostListener('mouseout')
hideFromMouseOut() {
this.detachOverlay();
}
@HostListener('mousedown')
hideFromClick() {
this._enable = false;
this.destroyOverlay();
}
@HostListener('mouseup')
_enableTooltip() {
this._enable = true;
}
private createOverlay() {
const positionStrategy = this.overlayPositionBuilder
.flexibleConnectedTo(this.elementRef)
.withPositions(ArOverlayPosition.getConnectedPosition(this.placement));
this.overlayRef = this.overlay.create({
positionStrategy,
scrollStrategy: this.overlay.scrollStrategies.close()
});
}
private destroyOverlay() {
if (this.overlayRef) {
this.overlayRef.dispose();
this.overlayRef = null;
}
}
private detachOverlay() {
if (this.overlayRef && this.overlayRef.hasAttached()) {
this.overlayRef.detach();
}
}
}