2👍
✅
You can disable the standard legend and generate your own HTML legend instead.
componentDidMount() {
this.generateLegend(document.getElementById("legend"), this.refs.chart.chartInstance);
}
generateLegend(div, chart) {
let ul = document.createElement("ul");
chart.data.labels.forEach((l, i) => {
let ds = chart.data.datasets[0];
let bgColor = ds.backgroundColor[i];
let border = ds.borderWidth + "px solid " + ds.borderColor[i];
let li = document.createElement("li");
let symbolSpan = document.createElement("span");
symbolSpan.style.cssText = "width: 6px; height: 14px; background-color:" + bgColor + "; border:" + border + ";";
li.appendChild(symbolSpan);
let labelSpan = document.createElement("span");
labelSpan.innerHTML = l;
symbolSpan.onclick = function() {
let hidden = !chart.getDatasetMeta(0).data[i].hidden;
chart.getDatasetMeta(0).data[i].hidden = hidden;
labelSpan.style.textDecoration = hidden ? "line-through" : "";
chart.update();
};
labelSpan.onclick = function() {
let hidden = !chart.getDatasetMeta(0).data[i].hidden;
chart.getDatasetMeta(0).data[i].hidden = hidden;
labelSpan.style.textDecoration = hidden ? "line-through" : "";
chart.update();
};
li.appendChild(labelSpan);
ul.appendChild(li);
});
div.appendChild(ul);
}
Please take a look at this StackBlitz and see how it works.
Source:stackexchange.com