Using Chart.js on Angular 4

后端 未结 3 1591
灰色年华
灰色年华 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:49

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

    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 example for implementation methods using typescript.

    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.

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

提交回复
热议问题