Reputation: 183
I am having an issue getting the datalabels plugin to function correctly with my chart in my Angular 5 app.
The chart is displaying as expected with the exception of no labels are being created by the plugin. No console errors are being generated either which seems odd.
my import section looks like:
import {Chart} from 'chart.js';
import 'chartjs-plugin-datalabels';
My chart creation section looks like:
ngAfterViewInit() {
this.canvas = document.getElementById(this.chartID);
this.canvas.height = this.graphHeight;
this.ctx = this.canvas.getContext('2d');
this.myChart = new Chart(this.ctx, {
type: 'horizontalBar',
data: {
labels: this.chartLabels,
datasets: [{
label: 'Percentage',
data: this.chartValues,
borderWidth: 1,
backgroundColor: '#a32d31',
datalabels: {
align: 'end',
anchor: 'start'
}
}]
},
options: {
legend: {
display: false
},
maintainAspectRatio: false,
plugins: {
datalabels: {
color: 'white',
font: {
weight: 'bold'
},
formatter: Math.round
}
}
}
});
}
Is there a separate step needed at some point to register the plugin (the samples provided don't show that). Any ideas or suggestions to get this working? The chart itself looks fine with the exception of the plugin output not being there.
Upvotes: 10
Views: 14236
Reputation: 449
Ok, I'm using Angular V13 with chart.js v 3.7 and chartjs-plugin-datalabels v 2. I struggled a lot trying to get things working. The problem was not errors, but the labels were just not appearing. Turned out that I had to add .default to the plugin reference:
public chartPlugins = [pluginDataLabels.default];
Now you can bind this chartPlugins variable to the canvas:
<canvas baseChart
[data]="lineChartData"
[options]="lineChartOptions"
[type]="lineChartType"
[plugins]="chartPlugins"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
And then it works!
Upvotes: 3
Reputation: 39075
I know this isn't exactly the same problem that the OP had, but I had a bit of trouble with the Angular CLI compiling the code properly.
angular.json:
{
"projects": {
"myProject": {
"architect": {
"build": {
"options": {
"scripts": [
"node_modules/chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.js"`
create index.d.ts
file with contents:
declare module 'chartjs-plugin-datalabels'
import as follows:
import ChartDataLabels from 'chartjs-plugin-datalabels';
Upvotes: 5
Reputation: 91
install chartjs-plugin-datalabel by
npm install chartjs-plugin-datalabels --save
Then import the same in component by
import ChartDataLabels from 'chartjs-plugin-datalabels';
and add
labels:[]
..
datasets[]
..
plugin:[ChartDataLabels]
This worked for me . Hope it will work.
Upvotes: 9
Reputation: 183
Hopefully this helps others:
The error was a result of the axis min value not being defaulted to zero. Once that was applied to the axes all functions as expected.
Upvotes: 1