[Chartjs]-Changing chart options dynamically in Chart.js

1๐Ÿ‘

โœ…

That is not correct. To change the options use chart.options where chart = this.chart.

Instead of updating the data, go through the chart object to update the data.
Then use chart.update(). This uses the click event to see if only one legend is displaying. If it is then it displays the data labels.

legend: {
    display: true,
    onClick: function (e, legendItem) {
        var index = legendItem.datasetIndex;
        var ci = this.chart;
        var meta = ci.getDatasetMeta(index);

        // See controller.isDatasetVisible comment
        meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
        var cnt = 0;
        for (var i = 0; i < ci.data.datasets.length; i++) {
            if (!ci.data.datasets[i]._meta[0].hidden) {
                cnt++;
            }
        }
        if (cnt === 1) {
            ci.options.plugins.datalabels.display = true;
        }
        else {
            ci.options.plugins.datalabels.display = false;
        }
        ci.update();
    }
}

1๐Ÿ‘

Since the options can only be set when the chart is created, it sounds like you need to recreate/redraw the charts when you have new options to use. You could set a listener on the radio buttons to recreate the charts with the new options.

Leave a comment