[Chartjs]-Update Chart.js plugin

4๐Ÿ‘

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:

  1. I replaced the function keyword in the plugin with an arrow function so that I could use a class variable using the this keyword.

  2. 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();            
}

Leave a comment