Hi,
I'm trying to create a simple doughnut chart using Chart.js and datalabels in Angular 5.
I followed the docs but could not get it to work.
Specs:
Angular v5
Chart,js v2.7.2
chartjs-plugin-datalabels v0.3.0
Here is my code:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Chart } from 'chart.js';
@Component({
selector: 'app-root',
template: `
<div style="height: 300px; width: 300px">
<canvas #myChart>{{doughnut}}</canvas>
</div>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
public doughnut = [];
@ViewChild('myChart') chart: ElementRef;
ngOnInit() {
this.doughnut = new Chart(this.chart.nativeElement, {
type: 'doughnut',
data: {
labels: ['a', 'b', 'c', 'd'],
datasets: [{
backgroundColor: '#2c82be',
data: [12, 34, 23, 65],
datalabels: {
anchor: 'end'
}
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
datalabels: {
backgroundColor: function (context) {
return context.dataset.backgroundColor;
},
borderColor: 'white',
borderRadius: 25,
borderWidth: 2,
color: 'white',
font: {
weight: 'bold'
},
formatter: Math.round
}
},
legend: {
display: true
},
}
});
}
}
The chart is created but not the labels.
Any help is appreciated.
Edit(SB): code formatting
Where did you import this plugin (import * from 'chartjs-plugin-datalabels';)? Though, I'm not sure that's the way to go since I'm not familiar with Angular. Maybe @Sadi-1992 (#5) or @bitflower (#12) have some inputs, else that's a question you would better ask on stackoverflow.
Hello @sidv93,
As @simonbrunel noted, you need to import plugin in your component first. Please, add import 'chartjs-plugin-datalabels'; to your import section and it should work as expected.
@deavy and @simonbrunel
Thank you guys. Appreciate the help. It worked
Most helpful comment
Hello @sidv93,
As @simonbrunel noted, you need to import plugin in your component first. Please, add
import 'chartjs-plugin-datalabels';to your import section and it should work as expected.