问题描述
我正在使用 Angular2-rc4 和 angular-cli webpack,并希望实现一个 chart.js 库.
I'm using Angular2-rc4 with angular-cli webpack and would like to implement a chart.js library.
我已将 chart.js 安装到我的项目中,使用:
I've installed chart.js to my project using:
npm install chart.js --save
然后我尝试在我的组件中导入chart.js:
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'.
我做错了什么?
推荐答案
我遇到了类似的问题,原来我引用的是一个旧示例.
I had a similar issue, it turned out I was referencing an old example.
首先,正如您已经正确完成的那样,使用 NPM 安装库:
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';
要启动并运行一个快速示例,请查看 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.
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
}
}
}
);
}
}
这篇关于如何在 Angular2 中实现 chart.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!