[Chartjs]-How to unregister a chart plugin?

5👍

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.

Leave a comment