krispo / ng2-nvd3

Angular2 component for nvd3
http://krispo.github.io/ng2-nvd3/
MIT License
328 stars 104 forks source link

How can I invoke clearElement() method to clean a chart? #111

Open surfercoder opened 7 years ago

surfercoder commented 7 years ago

Hi there!

I am using this package and it is working incredibly right. The only issue I have had so far is that if I have a tooltip and I re-draw the chart, the old tooltip remains there.

Checking the source code I found you have a method to clean the chart and its tooltips but I have no idea how to grab the chart element and invoke the method since I just have the nvd3 directive on the HTML with options and data inputs.

UPDATE:

I could grab the element with ViewChild, so this is what I have so far:

HTML:

<nvd3 #chartElement [options]="chart.options" [data]="chart.data">

TS:

@ViewChild('chartElement') public chartElement: any; // I have to use any, if I use ElementRef I loose many properties and methods. Then I invoke the clearElement method like this.

this.chartElement.clearElement();

And even when the chart was successfully cleaned, the tooltips were still there and I cannot find a way to remove them.

SOLUTION:

Guys, since the clearElement() method removes everything except for the tooltips, inspecting the DOM I found that tooltips elements have the CSS class 'nvtooltip', so I remove them manually like this:

if (this.chartElement) {
  // Clear chart 
  this.chartElement.clearElement();
 // Grab all tooltips and remove them
  const tooltipElements = document.getElementsByClassName('nvtooltip');
  Array.prototype.map.call(tooltipElements, tooltipEmement => {
    tooltipEmement.remove();
  });
}

I hope you find this useful!

Best regards.