Using Chart.js on Angular 4

后端 未结 3 1602
灰色年华
灰色年华 2020-12-05 05:15

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 comp

3条回答
  •  余生分开走
    2020-12-05 05:56

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

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

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

    1. Update project.config.ts to 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.ts to 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:

提交回复
热议问题