如何在Angular 2中实现Chart.js? [英] How implement Chart.js in Angular 2?

查看:70
本文介绍了如何在Angular 2中实现Chart.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2 V4.0.0的最新版本,并且我希望在我的项目中使用Chart.js库中的图形,而不会带来很多麻烦。

I am using the latest version of Angular 2, V4.0.0 and I want to use graphs from the Chart.js library in my project without many complications.

如何在我的角度项目中实现在最终生产中不会给我带来问题的Chart.js?

How can I implement Chart.js in my angular project that does not give me problems in the final production?

推荐答案

您可以实现Chart.js的简单说明如下:

You can implement Chart.js in a simple way with the following instructions:

1。使用angular-cli创建一个新项目,如果您已经创建了一个项目,则跳过

ng new example-chartjs

2。在您的项目中安装Chart.js

npm install chart.js --save

3。将图表导入其组件

import Chart from 'chart.js';

4。在您的视图和组件中使用图表

在您的视图中:

<canvas id="myChart" width="400" height="400"></canvas>

在您的组件中:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}

该组件应类似于以下内容

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

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}

另一种替代方法用途是包括文件 .angular-cli.json中的库。

Another alternative to use is to include the library from the file ".angular-cli.json"

1。在脚本中包括库

"styles": [
  "styles.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/chart.js/dist/Chart.min.js"
]

2。在控制器中声明一个类型为 any的变量

declare var Chart:any;

3。在您的视图和组件中使用图表

在您的视图中:

<canvas id="myChart" width="400" height="400"></canvas>

在您的组件中:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}

该组件应类似于以下内容

import { Component, OnInit } from '@angular/core';

declare var Chart:any;

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}

这篇关于如何在Angular 2中实现Chart.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆