Search code examples
angulard3.jstooltippie-chart

Unable to position tooltip on d3.js pie chart in Angular


I'm trying to integrate a working d3 code in an Angular project.

Everything's right except the tooltip position. It should normally appears above the focused part of the pie chart but :

  1. it always appears at the bottom of the graph when the tooltip is a div in the body

  2. it's never displayed when I add the tooltip to the svg element

I tried

.style('z-index', '9999')
.style("position", "absolute") 

and many other things but it doesn't work.

When I debug in order to see where my element is positioned in the svg (when add it to the svg), the tooltip element exists at the correct position but its dimensions are 0x0.

Same thing when I add height and width via .attr('height', '100px').attr('width', '100px').

And it doesn't change anything when I modify directly the html in the browser...

You can see the complete code on stackblitz.

I've no more idea to solve this problem. Any idea ?

Thanks in advance :-)


Solution

  • In D3 v6, the API to add a tooltip has changed, so you can change your function accordingly:

    onst arcs = this.arcs
    const onMouseover = (event, d) => {
      const e = arcs.nodes();
      const i = e.indexOf(this);
      const pointerEvent = d3.pointer(event)
    //...
    }
    
    this.arcs
      .on("mouseover", onMouseover)
    

    For your tooltip, what you need is a container div that has both the SVG and the tooltip in it:

    <div class="container">
      <svg></svg>
      <div class="tooltip"></div>
    </div>
    

    Set the container to be position: relative, and the tooltip to position: absolute so that its position depends on the parent, and thus on the SVG itself. Then you can position it with style():

    tooltip
      .style("left", `${d3.pointer(event)[0]}px`)
      .style("top", `${d3.pointer(event)[1]}px`)
    

    See d3.pointer().