Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5 chart.js datalabels plugin

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.

like image 266
Dave S. Avatar asked Feb 05 '23 00:02

Dave S.


2 Answers

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.

like image 147
sumeet kumar bal Avatar answered Feb 06 '23 13:02

sumeet kumar bal


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';

like image 25
Stephen Paul Avatar answered Feb 06 '23 15:02

Stephen Paul