Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unregister a chart plugin?

Tags:

chart.js

Using Chart.pluginService.register I drew a line on chart for some requirement on Page B (lets say). I go to Page B from Page A.

Now when I go back to page A and again go to Page B, the line drawn on the chart starts getting darker.

How to unregister that plugin when I go back to Page A?

I saw an unregister and clear function on this source: https://github.com/chartjs/Chart.js/blob/647dc582cd85fc8e25d49cf0e38d459c582b2652/src/core/core.plugin.js

Unregister function has no effect. Clear function clears the previously drawn line but the legend of the chart disappears.

like image 298
DR93 Avatar asked Oct 12 '18 11:10

DR93


1 Answers

Adding

ngOnDestroy() {
  Chart.pluginService.unregister(this.horizonalLinePlugin);
}

in your ProductDetailComponent shoud do the trick.

https://stackblitz.com/edit/angular-uxfwqb?file=src/app/product-detail/product-detail.component.ts

The problem here is that if you have multiple chart components visible at the same time, the plugin will be visible in all the other charts.

The better fix:

  1. register the plugin only once, outside of ngInit... directly in the module file or somewhere globally. This will impact all the charts in the entire application but will make it unnecessary to unregister it so it is clear that it's something global that impacts all charts.

  2. create your own wrapper component/directive over chart.js (or a pull request for angular2-chartjs) that can accept a plugins input and pass it to the Chart constructor http://www.chartjs.org/docs/latest/developers/plugins.html: var chart1 = new Chart(ctx, { plugins: [plugin] }); This will allow you to have a chart with the plugin and a chart without it, so no need to register/unregister global plugins.

like image 197
Andrei Tătar Avatar answered Nov 04 '22 01:11

Andrei Tătar