7

我不确定如何将插件准确地导入 ng2-charts,特别是注释插件。我正在使用 Angular2 / Ionic2。似乎没有任何文档或答案。

4

4 回答 4

7

我会避免像这样声明图表。相反,您可以这样做,import {Chart} from 'chart.js'因为它无论如何都是 ng2-charts 的子依赖项。

通过这种方法,您的 IDE 仍然可以进行自动完成,并且您不会告诉 Angular 只是相信有一个叫做 Chart 的东西。

为了保持一致,您还应该将其添加到您的 package.json 中。

于 2018-01-29T15:51:24.603 回答
4

也许跟随这个线程(https://github.com/valor-software/ng2-charts/issues/496)以防出现更“官方”的方式,但这是我所做的:

在组件的顶部:

declare var Chart: any;

这将阻止 TypeScript 抱怨并让您访问 Chart 对象。

然后你可以使用:

Chart.pluginService.register

这是我正在使用的插件的代码示例: https ://github.com/chartjs/Chart.js/issues/78#issuecomment-220829079

更新(2018 年 5 月): 此答案可能不再有效或最好的方法。

于 2017-02-01T18:28:22.140 回答
1

例如在圆环图的中心绘制我发现在选项动画中使用它的解决方法,所以不需要重新注册插件

    animation: {
      onProgress: function(chart) {
        let width = chart.chart.width,
          height = chart.chart.height,
          ctx = chart.chart.ctx;

        ctx.restore();
        let fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";
        ctx.fillStyle = '#dddddd';

        let text = "75%",
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = height / 2;

        ctx.fillText(text, textX, textY);
        ctx.save();
      },
      onComplete: function(chart) {
        let width = chart.chart.width,
          height = chart.chart.height,
          ctx = chart.chart.ctx;

        ctx.restore();
        let fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";
        ctx.fillStyle = '#dddddd';

        let text = "75%",
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = height / 2;

        ctx.fillText(text, textX, textY);
        ctx.save();
      },
    },

于 2020-01-15T09:30:33.453 回答
0

我花了很长时间才弄清楚,所以在这里添加对我有用的东西,以防其他人在 Angular 2+ 中遇到这个问题:

app.module.ts:

import * as ChartLabels from 'chartjs-plugin-labels';

...

export class AppModule {
  constructor() {
    BaseChartDirective.unregisterPlugin(ChartLabels); // this makes chart plugins work in components
  }
}

组件.ts:

... // other imports
import * as ChartLabels from 'chartjs-plugin-labels';

  ... // component annotations
  export class MyChartComponent {

    ... // other chart members

    public doughnutChartPlugins = [ChartLabels];
    public doughnutChartOptions: ChartOptions = { 
      responsive: true,
      maintainAspectRatio: true,
      plugins: {
        labels: {
          render: 'value',
        }
      },
    };

   ... // constructor and so on

组件.html

<canvas baseChart
    [data]="doughnutChartData"
    [labels]="doughnutChartLabels"
    [chartType]="doughnutChartType"
    [options]="doughnutChartOptions"
    [plugins]="doughnutChartPlugins"
    [legend]="doughnutChartLegend"
    [colors]="doughnutChartColors"
>
</canvas>
于 2021-06-24T14:23:38.197 回答