Chartjs-Failed to use Chart.js using Angular2

0👍

Chart.js needs to be wrapped so it will work with typescript. Using import {chart} from 'chart.js'; won’t work. Try a different npm library like this one:

https://www.npmjs.com/package/ng2-charts

I’ve had success with it. Should fix your issue.

You won’t need to import chart at all.

Just include your cart in your html. Something like this:

 <canvas baseChart height="200"
        [datasets]="lineChartData"
        [labels]="lineChartLabels"
        [options]="lineChartOptions"
        [colors]="lineChartColors"
        [legend]="lineChartLegend"
        [chartType]="lineChartType"
  ></canvas>

Then access it in your component. Something like this:

lineChartData: Array<any>;
lineChartLabels: string[] = [..data..    
  ];

  lineChartOptions: any = {
    responsive: true,
    animation: false,

  };
  lineChartColors: Array<any> = [
    { // grey
      backgroundColor: 'rgba(33,150,243,0.2)',
      borderColor: 'rgba(33,150,243,1)',
      pointBackgroundColor: 'rgba(33,150,243,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(33,150,243,0.8)'
    },
    { // dark grey
      backgroundColor: 'rgba(76,175,80,0.2)',
      borderColor: 'rgba(76,175,80,1)',
      pointBackgroundColor: 'rgba(76,175,80,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(76,175,80,1)'
    },
    { // grey
      backgroundColor: 'rgba(244,67,54,0.2)',
      borderColor: 'rgba(244,67,54,1)',
      pointBackgroundColor: 'rgba(244,67,54,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(244,67,54,0.8)'
    },
    { // grey
      backgroundColor: 'rgba(103,58,183,0.2)',
      borderColor: 'rgba(103,58,183,1)',
      pointBackgroundColor: 'rgba(103,58,183,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(103,58,183,0.8)'
    },
    { // grey
      backgroundColor: 'rgba(255,152,0,0.2)',
      borderColor: 'rgba(255,152,0,1)',
      pointBackgroundColor: 'rgba(255,152,0,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(255,152,0,0.8)'
    },
    { // grey
      backgroundColor: 'rgba(96,125,139,0.2)',
      borderColor: 'rgba(96,125,139,1)',
      pointBackgroundColor: 'rgba(96,125,139,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(96,125,139,0.8)'
    }    
  ];

  lineChartLegend: boolean = true;
  lineChartType: string = 'line';

Leave a comment