angular 5 chart.js 数据标签插件

Dav*_* S. 8 javascript chart.js angular5

我在使数据标签插件与我的 Angular 5 应用程序中的图表一起正常工作时遇到问题。

除了插件没有创建标签外,图表按预期显示。也没有生成控制台错误,这看起来很奇怪。

我的导入部分看起来像:

import {Chart} from 'chart.js';
import 'chartjs-plugin-datalabels';
Run Code Online (Sandbox Code Playgroud)

我的图表创建部分如下所示:

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
          }
        }
      }
    });

  }
Run Code Online (Sandbox Code Playgroud)

在某些时候是否需要单独的步骤来注册插件(提供的示例没有显示)。有什么想法或建议可以让这个工作吗?图表本身看起来不错,除了插件输出不在那里。

小智 6

安装chartjs-plugin-datalabel

npm install chartjs-plugin-datalabels --save
Run Code Online (Sandbox Code Playgroud)

然后在组件中导入相同的内容

import ChartDataLabels from 'chartjs-plugin-datalabels';
Run Code Online (Sandbox Code Playgroud)

并添加

labels:[]
..
datasets[]
..
plugin:[ChartDataLabels]
Run Code Online (Sandbox Code Playgroud)

这对我有用。希望它会起作用。


Ste*_*aul 5

我知道这与 OP 遇到的问题并不完全相同,但我在 Angular CLI 正确编译代码时遇到了一些麻烦

角度.json:

{
  "projects": {
    "myProject": {
      "architect": {
        "build": {
          "options": {
            "scripts": [
              "node_modules/chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.js"`
Run Code Online (Sandbox Code Playgroud)

创建index.d.ts包含内容的文件:

declare module 'chartjs-plugin-datalabels'
Run Code Online (Sandbox Code Playgroud)

导入如下:

import ChartDataLabels from 'chartjs-plugin-datalabels';


Dav*_* S. 1

希望这对其他人有帮助:

该错误是由于轴最小值未默认为零造成的。一旦将其应用于轴,所有功能都会按预期运行。