首页 > 解决方案 > Angular 11 中 ng2-charts 的注释问题

问题描述

我需要在我的图表中显示一条固定线(如图像中的“测试标签”):

在此处输入图像描述

所以我在我的 Angular 11 项目中添加了 chartjs-plugin-annotation,所以我有这些版本:

"chart.js": "^2.9.3",
"chartjs-plugin-annotation": "^1.0.2",
"ng2-charts": "^2.3.0",

然后我添加了我的选项:

    this.chartOptions = {
      responsive: true,
      scales: {
        xAxes: [{}],
        yAxes: [
          {
            id: 'y-axis-0',
            position: 'left',
          }
        ]
      },
      annotation: {
        annotations: [{
          type: 'line',
          drawTime: 'afterDatasetsDraw',
          id: 'strip-line-1',
          mode: 'horizontal',
          scaleID: 'y-axis-0',
          value: tagvalue,
          borderColor: 'red', // '#feaf00',
          borderWidth: 3
        }]
      }
    };
  }

但是没有显示任何线条......所以我发现我必须注册这个,但它不起作用

import * as ChartAnnotation from 'chartjs-plugin-annotation';

Chart.pluginService.register(ChartAnnotation);

我有:

TS2559: Type 'typeof import("C:/.../node_modules/chartjs-plugin-annotation/types/index")' has no properties in common with type 'Plugin'.

这是因为: 在此处输入图像描述

它是chartjs-plugin-annotation 错误吗?我需要更改一些依赖项?

标签: angularchart.jsng2-chartsangular-chartchartjs-plugin-annotation

解决方案


如注释插件文档中所述,如果您使用的是 chart.js 版本 2,则需要使用版本 0.5.7

重要说明 对于 Chart.js 2.4.0 到 2.9.x 的支持,请使用此插件的 0.5.7 版本 v0.5.7 的文档可以在 GitHub 上找到。

因此,您需要删除注释插件并安装较低版本或更新到 chart.js 版本 3

npm uninstall chartjs-plugin-annotation

npm install chartjs-plugin-annotation@0.5.7

推荐阅读