Chartjs-Chart.js update chart when legend label is hidden?

0👍

I know this is late but I hope this will also help other devs.

I also came across this issue, I found out that every time you try you click the legend, the callback of generateLabels also executes.

So you need to use the chart’s existing legendItems after the first generation to avoid overriding properties.

plugins: {
          legend: {
            labels: {
              generateLabels: (chart) => {
                if (chart.data.labels.length && chart.data.datasets.length) {
                  return chart.legend.legendItems ?? chart.data.labels.map((label, i) => ({
                    text: label,
                    fontColor: chart.data.datasets[0].backgroundColor[i],
                    fillStyle: chart.data.datasets[0].backgroundColor[i],
                    strokeStyle: '#fff',
                    hidden: myChart ? myChart.getDatasetMeta(0).data[i].hidden : false
                  }));
                }
              },
            },

Leave a comment