Chartjs-OnClick event on Custom legends Chart.js / Angular 5

2👍

It’s not a neat solution but it’s the only one I found so far.
Instead of using the onclick event I added an eventListener after adding the new legend. Then you need to do minor changes to the updateDataset() function.

The legendCallback should look something like this:

legendCallback: (chart) => {
      var legendHtml = [];
      legendHtml.push('<table>');
      legendHtml.push('<tr>');
      for (var i=0; i<chart.data.datasets.length; i++) {
          legendHtml.push('<td><div class="chart-legend" style="background-color:' + chart.data.datasets[i].backgroundColor + '"></div></td>');                    
          if (chart.data.datasets[i].label) {
              legendHtml.push('<td class="chart-legend-label-text" id="' + chart.id + '_' + chart.legend.legendItems[i].datasetIndex + '">' + chart.data.datasets[i].label + '</td>');
          }
      }                                                                                  
      legendHtml.push('</tr>');                                                          
      legendHtml.push('</table>');
      return legendHtml.join("");                                                        
    },

And then add the listener and the updateDataset() function after the declaration of the Chart:

document.getElementById("customLegend" + this.chartId).innerHTML = myChart.generateLegend();
var legenTags = document.getElementsByClassName("chart-legend-label-text");
var updateDataset = function(e) {
  var id = e.currentTarget.id;
  var index = id.split('_')[1];
  var chartId= id.split('_')[0];
  if (myChart.id == chartId) {
    var meta = myChart.getDatasetMeta(index);
    // See controller.isDatasetVisible comment
    meta.hidden = meta.hidden === null? !myChart.data.datasets[index].hidden : null;

    // We hid a dataset ... rerender the chart
    myChart.update();
  }
}

for (var i = 0; i < legenTags.length; i++) {
  legenTags[i].addEventListener('click', updateDataset, false);
}

I hope it helps.
If anyone has a better solution please share.

Leave a comment