Trying to display datalabels on the a pie chart using chartjs library in LWC. Tried both version pairs for chartjs and chartjs datalabel plugins libraries (V4.2.1- chartjs & V2.2.0 - chartjs-datalabel-plugin) & (v2.8-chartjs & v1.0-chartjs-datalabel-plugin) as mentioned in few other posts. But unable to get the datalabels displayed. Below is my code. Must be missing something basic.
testChart.html
<template>
<div>
<canvas></canvas>
</div>
</template>
testChart.js
import { LightningElement } from 'lwc';
import chartjs from '@salesforce/resourceUrl/chartjs';
import { loadScript } from 'lightning/platformResourceLoader';
import ChartDataLabels from '@salesforce/resourceUrl/chartjsdatalabels';
export default class TestChart extends LightningElement {
chartJsInitialized = false;
renderedCallback() {
if (this.chartJsInitialized) {
return;
}
this.chartJsInitialized = true;
Promise.all([
loadScript(this, chartjs),loadScript(this, ChartDataLabels)
]).then(() => {
console.log('ChartJS and ChartJS Datalabels scripts loaded successfully.');
this.initializeChart();
}).catch(error => {
console.error(error);
});
}
initializeChart() {
const data = {
labels: ['Label 1', 'Label 2', 'Label 3'],
datasets: [{
data: [30, 50, 20],
backgroundColor: [
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)'
],
borderWidth: 1
}]
};
const options = {
responsive: false,
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
labels: {
value: {
color: 'blue'
}
}
}
}
};
//chartjs.Chart.register(ChartDataLabels);
const chart = new window.Chart(this.template.querySelector('canvas'), {
type: 'pie',
data: data,
plugins: [ChartDataLabels],
options: options
});
}
}
Please help in finding the solution