Skip to content

Commit

Permalink
Update app
Browse files Browse the repository at this point in the history
  • Loading branch information
louiiuol authored Oct 28, 2024
1 parent bb1fe2c commit a6c6ed3
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/app/directives/tooltip.directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Directive, ElementRef, HostListener, Input, Renderer2 } from '@angular/core';

@Directive({
selector: '[libTooltip]'
})
export class TooltipDirective {
@Input('libTooltip') tooltipContent: string = '';
private tooltipElement: HTMLElement | null = null;

constructor(private el: ElementRef, private renderer: Renderer2) {}

@HostListener('mouseenter') onMouseEnter() {
if (!this.tooltipElement) {
this.showTooltip();
}
}

@HostListener('mouseleave') onMouseLeave() {
this.hideTooltip();
}

private showTooltip() {
this.tooltipElement = this.renderer.createElement('div');
this.renderer.appendChild(
this.tooltipElement,
this.renderer.createText(this.tooltipContent)
);

// Add HTML support
this.tooltipElement.innerHTML = this.tooltipContent;

this.renderer.appendChild(document.body, this.tooltipElement);
this.renderer.addClass(this.tooltipElement, 'tooltip');

const hostPos = this.el.nativeElement.getBoundingClientRect();
const tooltipPos = this.tooltipElement.getBoundingClientRect();

const top = hostPos.top - tooltipPos.height - 8;
const left = hostPos.left + (hostPos.width - tooltipPos.width) / 2;

this.renderer.setStyle(this.tooltipElement, 'position', 'absolute');
this.renderer.setStyle(this.tooltipElement, 'top', `${top}px`);
this.renderer.setStyle(this.tooltipElement, 'left', `${left}px`);
this.renderer.setStyle(this.tooltipElement, 'z-index', '1000');
}

private hideTooltip() {
if (this.tooltipElement) {
this.renderer.removeChild(document.body, this.tooltipElement);
this.tooltipElement = null;
}
}
}

0 comments on commit a6c6ed3

Please sign in to comment.