score:4

Accepted answer

if you are using typescript you just need to install the @types package

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

now typescript knows how to typecheck use of the package and the following will work.

import chart = require('chart.js'); // for commonjs users.

import chart from 'chart.js'; // for systemjs and/or babel users.

const mychart = new chart($('#chart1'), {});

note, i show two imports in the example above. remove whichever does not work at runtime but only keep one of them.

for systemjs + npm, add the following to the map section of your systemjs.config.js

"chart.js": "npm:chart.js/dist/chart.js"

optionally, if and only if you are using the ng2-charts wrapper, then run

npm install --save ng2-charts

and then add it you your primary ngmodule decorator factory's, imports array

import { chartsmodule } from 'ng2-charts/ng2-charts';

@ngmodule({
  imports: [
    chartsmodule
  ]
}) export class appmodule {}

score:-1

simple workaround is to add this to index.html:

<script src="node_modules/chart.js/dist/chart.bundle.min.js"></script>

i actually use primeng which have a charts component based on chart.js, also had issues. this was the quickest way to get up and running. make sure you reference the 'bundle' package.

score:0

change your import syntaxt to this :

import chart from "chart.js/dist/chart.bundle.min.js";

make sure you already did

npm install chart.js --save

if youalready did, in you node modules supposed to have nodemodules/chart.js

score:1

for an angular cli project, you'd want to add the chart.js dependency in the .angular-cli.json in the scripts array property like this:

"scripts": [
    "../node_modules/chart.js/dist/chart.bundle.min.js"
]

otherwise you can import the library using syntax as follows:

import * as chart from 'chart.js'

that being said, i'd recommend using a library such as the one your suggested as you're going to have access to components, directives, and emitted events that will be easier to work with in your components.

hopefully that helps!

score:2

it's very simple to use in angular2...

  1. installation :

    npm install angular2-chartjs
    
  2. add chartmodule to your module :

    import { chartmodule } from 'angular2-chartjs';
    @ngmodule({
      imports: [ chartmodule ]
    })
    
    export class appmodule {
    }
    
  3. javascript

    type = 'line';
    data = {
      labels: ["january", "february", "march", "april", "may", "june", "july"],
      datasets: [{
        label: "my first dataset",
        data: [65, 59, 80, 81, 56, 55, 40]
      }]
    };
    options = {
      responsive: true,
      maintainaspectratio: false
    };
    
  4. html

    <chart [type]="type" [data]="data" [options]="options"></chart>
    

link: https://github.com/emn178/angular2-chartjs "documentation"

enjoy happy codeing. hopefully that helps!


Related Query

More Query from same tag