Javascript 在 Angular 4 上使用 Chart.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46328575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:23:56  来源:igfitidea点击:

Using Chart.js on Angular 4

javascriptangulartypescriptchart.js

提问by Gustavo

I'm trying to use Chart.js with Angular 4, I saw an example on the chart.js documents but it's using a < script > tag to pull the script so it doesn't work on the component. This is how I tried to fit into Angular:

我正在尝试将 Chart.js 与 Angular 4 一起使用,我在 chart.js 文档中看到了一个示例,但它使用 < script > 标签来拉取脚本,因此它在组件上不起作用。这就是我试图适应 Angular 的方式:

TS

TS

export class GraphicsComponent implements OnInit {

  ctx = document.getElementById("myChart");
  myChart = new Chart(this.ctx, {
    type: 'pie',
    data: {
        labels: ["New", "In Progress", "On Hold"],
        datasets: [{
            label: '# of Votes',
            data: [1,2,3],
            backgroundColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
      responsive: false,
      display:true
    }
  });

  constructor() { }

  ngOnInit() {
  }

}

HTML

HTML

<canvas id="myChart" width="700" height="400"></canvas>

Any idea how I would make it work?

知道我将如何使它工作吗?

EDIT:I have updated my code with the import and I'm now receiving an error.

编辑:我已经用导入更新了我的代码,我现在收到一个错误。

Import Code:

进口代码:

import * as Chart from 'chart.js'

Error on chrome console:

chrome 控制台上的错误:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'length' of null
TypeError: Cannot read property 'length' of null
    at Object.acquireContext (platform.dom.js:333)
    at Chart.construct (core.controller.js:74)
    at new Chart (core.js:42)
    at new GraphicsComponent (graphics.component.ts:12)
    at createClass (core.es5.js:10922)
    at createDirectiveInstance (core.es5.js:10756)
    at createViewNodes (core.es5.js:12197)
    at createRootView (core.es5.js:12092)
    at callWithDebugContext (core.es5.js:13475)
    at Object.debugCreateRootView [as createRootView] (core.es5.js:12792)
    at Object.acquireContext (platform.dom.js:333)
    at Chart.construct (core.controller.js:74)
    at new Chart (core.js:42)
    at new GraphicsComponent (graphics.component.ts:12)
    at createClass (core.es5.js:10922)
    at createDirectiveInstance (core.es5.js:10756)
    at createViewNodes (core.es5.js:12197)
    at createRootView (core.es5.js:12092)
    at callWithDebugContext (core.es5.js:13475)
    at Object.debugCreateRootView [as createRootView] (core.es5.js:12792)
    at resolvePromise (zone.js:795)
    at resolvePromise (zone.js:766)
    at zone.js:844
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at <anonymous>

回答by Z. Bagley

You can install the package, along with the types for full functionality in a typescript environment such as Angular:

您可以在打字稿环境(例如 Angular)中安装该包以及完整功能的类型:

npm install --save chart.js && npm install --save-dev @types/chart.js

npm install --save chart.js && npm install --save-dev @types/chart.js

Then in your component you can now import * as Chart from 'chart.js'and use it in your typescript environment. Check out this examplefor implementation methods using typescript.

然后在您的组件中,您现在import * as Chart from 'chart.js'可以在打字稿环境中使用它。查看此示例以了解使用打字稿的实现方法。

Because you need to get the canvas from the DOM you need to make sure it's rendered before attempting to access it. This can be accomplished with AfterViewInit.

因为您需要从 DOM 获取画布,所以在尝试访问它之前需要确保它已呈现。这可以通过AfterViewInit.

import { Component, AfterViewInit } from '@angular/core';
import * as Chart from 'chart.js'

export class MyChartComponent implements AfterViewInit {

  canvas: any;
  ctx: any;

  ngAfterViewInit() {
    this.canvas = document.getElementById('myChart');
    this.ctx = this.canvas.getContext('2d');
    let myChart = new Chart(this.ctx, {
      type: 'pie',
      data: {
          labels: ["New", "In Progress", "On Hold"],
          datasets: [{
              label: '# of Votes',
              data: [1,2,3],
              backgroundColor: [
                  'rgba(255, 99, 132, 1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 206, 86, 1)'
              ],
              borderWidth: 1
          }]
      },
      options: {}
    });
  }

}

回答by Dave Skender

In my Angular 6.1 site, I am using chart.js by itself in mgechev/angular-seed.

在我的 Angular 6.1 站点中,我在mgechev/angular-seed单独使用 chart.js 。

As of writing this response, Chart.js developers have some work to doto make exporting its members compliant with newer standards so rollups may be problematic.

在撰写此回复时,Chart.js 开发人员有一些工作要做,以使导出其成员符合更新的标准,因此汇总可能会出现问题。

To get Chart.js 2.7.x to work after installing package chart.jsand types @types/chart.jsin this angular-seed, all I needed to do is:

为了在这个 angular-seed 中安装包chart.js和类型后让 Chart.js 2.7.x 工作@types/chart.js,我需要做的就是:

  1. Update project.config.tsto include ROLLUP_NAMED_EXPORTS to get rollup to work properly (if you're using a rollup).

    this.ROLLUP_NAMED_EXPORTS = [
      ...this.ROLLUP_NAMED_EXPORTS,
      { 'node_modules/chart.js/src/chart.js': ['Chart'] }
    ];
    
  2. Update project.config.tsto include additional packages. This seed uses SystemJS config. This might vary if you're using something else.

    // Add packages
    const additionalPackages: ExtendPackages[] = [
     { name: 'chart.js', path: 'node_modules/chart.js/dist/Chart.bundle.min.js' },
    
      ...
    
    ];
    
  3. In your component

    import { Chart } from 'chart.js';
    
    ...
    
    export class MyComponent implements OnInit {
    
    @ViewChild('myChart') myChartRef: ElementRef;
    chartObj: Chart;
    
    ...
    }
    

    Then load chart configuration in ngOnInit() per Chart.js documentation

  4. HTML will look something like this:

    <div class="chart-container">
       <canvas #myChart></canvas>
    </div>
    
  1. 更新project.config.ts以包含 ROLLUP_NAMED_EXPORTS 以使汇总正常工作(如果您使用汇总)。

    this.ROLLUP_NAMED_EXPORTS = [
      ...this.ROLLUP_NAMED_EXPORTS,
      { 'node_modules/chart.js/src/chart.js': ['Chart'] }
    ];
    
  2. 更新project.config.ts以包含其他软件包。此种子使用 SystemJS 配置。如果您使用其他东西,这可能会有所不同。

    // Add packages
    const additionalPackages: ExtendPackages[] = [
     { name: 'chart.js', path: 'node_modules/chart.js/dist/Chart.bundle.min.js' },
    
      ...
    
    ];
    
  3. 在您的组件中

    import { Chart } from 'chart.js';
    
    ...
    
    export class MyComponent implements OnInit {
    
    @ViewChild('myChart') myChartRef: ElementRef;
    chartObj: Chart;
    
    ...
    }
    

    然后根据Chart.js 文档在 ngOnInit() 中加载图表配置

  4. HTML 将如下所示:

    <div class="chart-container">
       <canvas #myChart></canvas>
    </div>