如何将Chart.js chartjs-plugin-datalabels npm包导入Angular 7项目

guicsvcw  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(239)

我有一个Angular 7(Ionic 4)项目,我在那里试用Chart.js,需要能够自定义绘制饼图上的一些标签,因为我已经要求here
有人告诉我需要使用一个单独的包来完成这个任务,但是我不能使用npm包来导入一个Angular 项目。
我有以下版本:

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

我已经按照建议尝试了here,但是我得到了两个错误。
第一个vscode会产生下列错误:

此外,还添加了此处所述的额外内容。
在其他地方,据说导入如下:
import 'chartjs-plugin-datalabels';
但是我随后得到了编译错误:

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

我怎么才能让它工作呢?

goqiplq2

goqiplq21#

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 .

相关问题