Search code examples
angularangular-directive

Angular tooltip directive relative to mouse position


So far I have found many examples showing how to create a tooltip whose position is relative to the component to which we added the directive.

However, I can't find an example of a directive that, when hovering over a component, displays a tooltip relative to the mouse position.

How can i get this effect?


Example:

<tooltip></tooltip> <!-- default: display: none and position: absolute -->

<component-A [tooltip]="data"></component-A>
<component-B [tooltip]="data"></component-B>
<component-C [tooltip]="data"></component-C>
<!-- show tooltip on mousenter and update position on mousemove -->

Solution

  • Scalable solution:


    tooltipable.component.html - this component is wrapper which expects the child to be divided into two sections:

    • tooltip - section conditionally displayed (onMouseEnter)
    • body - normal section (always displayed)
    <app-tooltip [display]="this.display" [x]="this.x" [y]="this.y">
      <ng-content select="[tooltip]"></ng-content>
    </app-tooltip>
    
    <ng-content select="[body]"></ng-content>
    

    tooltip.component.html - this is a container for data to be displayed in the tooltip

    <div class="tooltip"
      [style.display]="this.display ? 'block' : 'none'"
      [style.top]="y + 'px'"
      [style.left]="x + 'px'"
    >
        <ng-content></ng-content>
    </div>
    

    some.component.html

    <app-tooltipable>
       <div tooltip>Hello tooltip!</div>
       <div body>Hello world!</div>
    </app-tooltipable>