Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

angular - How to implement chart.js in Angular2

I'm using Angular2-rc4 with angular-cli webpack and would like to implement a chart.js library.

I've installed chart.js to my project using:

npm install chart.js --save

Then I've tried to import the chart.js in my component:

import {Component, OnInit, ViewChild} from '@angular/core';
import 'chart.js/src/chart.js';
declare let Chart;

@Component({
  selector: 'app-dashboard',
  templateUrl: 'dashboard.component.html',
  styleUrls: ['dashboard.component.scss']
})
export class DashboardComponent {

  chart: Chart;

}

But I get an error in console log:

[default] /Applications/MAMP/htdocs/bridge/src/app/dashboard/dashboard.component.ts:12:9 
Cannot find name 'Chart'.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had a similar issue, it turned out I was referencing an old example.

First, as you've already correctly done, install the library using NPM:

npm install chart.js --save

Then, in your component, import the library:

import Chart from 'chart.js';

To get up and running with a quick example, have a look at the example code in the Chart.js documentation or see my example below.


dashboard.component.ts

import Chart from 'chart.js';
import { ViewChild, Component, ElementRef, OnInit } from '@angular/core';

@Component({
    selector: 'app-dashboard',
    template: '<canvas #donut></canvas>'
})

export class DashboardComponent implements OnInit {
    @ViewChild('donut') donut: ElementRef;

    constructor(
    ) { }

    ngOnInit() {
        let donutCtx = this.donut.nativeElement.getContext('2d');

        var data = {
            labels: [
                "Value A",
                "Value B"
            ],
            datasets: [
                {
                    "data": [101342, 55342],   // Example data
                    "backgroundColor": [
                        "#1fc8f8",
                        "#76a346"
                    ]
                }]
        };

        var chart = new Chart(
            donutCtx,
            {
                "type": 'doughnut',
                "data": data,
                "options": {
                    "cutoutPercentage": 50,
                    "animation": {
                        "animateScale": true,
                        "animateRotate": false
                    }
                }
            }
        );
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...