Is it possible to update chart.js plugins by using chart.update()
?
I've tried the following, but seems like the plugin is not updated.
let myChart;
function drawChart(chart) {
const ctx = document.getElementById("my-chart");
if (!myChart) {
myChart = new Chart(ctx, {
type: 'scatter',
data: chart.data,
options: chart.option,
plugins: chart.plugin
});
} else {
myChart.data = chart.data;
myChart.options = chart.option;
myChart.plugins = chart.plugin;
myChart.update();
}
}
Any idea would be appreciated, thank you.
I also tried re-supplying the plugin before chart update, but it was not getting called. So instead I modified my plugin to take the @Input()
component variable on whose change chart update is called.
Please look at my example -- I had to show a total % in the middle of the doughnut chart. For that I needed to call a plugin in the afterDraw
event. I made 2 changes:
I replaced the function keyword in the plugin with an arrow function so that I could use a class variable using the this
keyword.
Then I used this.total
in my plugin that would get the total % I wanted to show. So during chart update -- my new total (total is @Input()
variable) would be automatically updated.
if (!this.doughnutChart && this.doughnut) {
let ctx = this.doughnut.nativeElement.getContext("2d");
if (ctx) {
this.doughnutChart = new Chart(ctx, {
// The type of chart we want to create
type: 'doughnut',
// The data for our dataset
data: {
labels: this.labels,
datasets: [{
data: this.dataArray,
backgroundColor: this.colorsArray
}]
},
// Configuration options go here
options: this.chartOptions,
// Plugin property will help to place total count
// at the center of the doughnut after chart is rendered
plugins: [{
id: this.canvasId + '_plugin',
afterDraw: (chart) => { // Using arrow function here
chart.ctx.fillStyle = 'black'
chart.ctx.textBaseline = 'middle'
chart.ctx.textAlign = 'center'
chart.ctx.font = '17px Verdana'
// Using this.total here
chart.ctx.fillText(this.total + '%',
chart.canvas.clientWidth / 2,
(chart.canvas.clientHeight / 2) + (titlePadding * 7 + 2 - bottomPadding))
}
}]
});
}
}
else if (this.doughnutChart) {
// Update the chart
this.doughnutChart.data.datasets[0].backgroundColor = this.colorsArray;
this.doughnutChart.update();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With