How to import Chart.js chartjs-plugin-datalabels npm package into an Angular 7 project

匆匆过客 提交于 2019-12-23 02:08:12

问题


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...

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.`

Does anyone have any idea on how to get this working??

Thanks in advance!


回答1:


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.



来源:https://stackoverflow.com/questions/55622806/how-to-import-chart-js-chartjs-plugin-datalabels-npm-package-into-an-angular-7-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!