3

I have an Angular 7 (Ionic 4) project, where I trying out Chart.js and need to be able to custom draw some labels on a Pie chart, as I Have asked here.

I have been told I need to use a separate package for this, but I cannot get the import working for an Angular project, using the npm package.

I have the following version:

"chart.js": "^2.8.0",
"chartjs-plugin-datalabels": "^0.6.0",
....
"@angular/*": "^7.2.2",
"typescript": "~3.1.6"

I have tried as suggested here, but I get two errors.

First vscode gives the the following error:

enter image description here

Also, added the extra as described here.

Elsewhere, it is said to import as follows:

import 'chartjs-plugin-datalabels';

But I then get the compile error:

    `[ng] ERROR in node_modules/chartjs-plugin-datalabels/types/index.d.ts(5,16): error TS2665: Invalid module name in augmentation. Module 'chart.js' resolves to an untyped module at 'D:/dev/ionic/chartjstest/node_modules/chart.js/dist/Chart.js', which cannot be augmented.`

How can I get this working?

halfer
  • 19,824
  • 17
  • 99
  • 186
peterc
  • 6,921
  • 9
  • 65
  • 131
  • Logged this issue [here](https://github.com/chartjs/chartjs-plugin-datalabels/issues/130]) if anyone interested in following – peterc Apr 11 '19 at 07:41
  • try to use import * as chart from 'chartjs-plugin-datalabels' to see if work or not –  Apr 11 '19 at 10:52
  • @NgôHùngPhúc - yes, thanks, that ended up being the way to do it as also suggested on the github issue link above – peterc Apr 11 '19 at 11:23
  • I see they manage to fix this error here https://github.com/chartjs/chartjs-plugin-datalabels/issues/130#issuecomment-482069301 –  Apr 11 '19 at 11:41
  • 1
    I know of the global import solution, which would effect all the components. Is there any way to make it available for only the component where we are using it and not spill outside of that particular component? I'm using bunch of different types of charts on the same screen (different components though), now all the charts have data labels on them, which I don't want. – Nakul Sharma Jun 19 '19 at 03:43

1 Answers1

5

You can import the directive like this:

import * as pluginDataLabels from 'chartjs-plugin-datalabels';

You can use Plugins in your ChartOptions like this:

chartOptions: ChartOptions = {
  ...
  plugins: {
    pluginDataLabels 
  }

Another way is to call it in your chart:

public barChartPlugins = [pluginDataLabels];

You can see it done here.

However, both ways declare it globally. The only way I could figure out not to see them in all charts is to not display them.

chartOptions: ChartOptions = {
  ...
  plugins: {
    datalabels: {
      display: false
    }, 
  }

This also solves the Problem @NakulSharma has. You can see the plugin options here.

RobC
  • 22,977
  • 20
  • 73
  • 80
jalei005
  • 170
  • 1
  • 7