首页 > 语言 > JavaScript > 正文

在 Angular 中使用Chart.js 和 ng2-charts的示例代码

2024-05-06 15:12:47
字体:
来源:转载
供稿:网友

Chart.js是一个流行的JavaScript图表库,ng2图表是Angular 2+的包装器,可以轻松地将Chart.js集成到Angular中。 我们来看看基本用法。

安装

首先,在项目中安装 Chart.js 和 ng2-charts:

# Yarn:$ yarn add ng2-charts chart.js# or npm $ npm install ng2-charts charts.js --save

当然 ,如果你是使用Angular CLI构建的项目,你也可以很容易的添加Chart.js 添加.angular-cli.json配置文件中,以便将它与应用绑定在一直:

//: .angular-cli.json (partial)"script": [ "../node_modules/chart.js/dist/Chart.min.js"]

现在,你需要在你的 app 模块或功能模块导入 ng2-charts 的ChartsModule:

//: app.module.tsimport { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { ChartsModule } from '@angular/charts';import { AppComponent } from './app.component';@NgModule({ declarations: [ AppComponent ], imports: [  BrowserModule,  ChartsModule ], providers: [], bootstrap: [ AppComponent ]})export class AppModule {}

使用

ng2-charts 给我们提供了一个可以应用于HTML canvas元素的baseChart指令。 以下是一个示例,其中显示了一些用于输入的选项以及该指令输出的chartClick事件:

//: app.component.html<div style="width: 40%;"> <canvas   baseChart   [chartType]="'line'"   [datasets]="chartData"   [labels]="chartLabels"   [options]="chartOptions"   [legend]="true"   (chartClick)="onChartClick($event)"> </canvas></div>

这就是组件类现在的样子:

//: app.component.tsimport { Component } from '@angular/core';@Component({ ... })export class AppComponent { chartOptions = {  responsive: true }; chartData = [  { data: [330, 600, 260, 700], label: 'Account A' },  { data: [120, 455, 100, 340], label: 'Account B' },  { data: [45, 67, 800, 500], label: 'Account C' } ]; chartLabels = ['January', 'February', 'Mars', 'April']; onChartClick(event) {  console.log(event); }}

选项

以下就是不同的可选输入项:

chartType

设置图表的基本类型, 值可以是pipe,doughnut,bar,line,polarArea,radar或horizontalBar。

legend

一个布尔值,用于是否在图表上方显示图例。

datasets

包含数据数组和每个数据集标签的对象数组。

data

如果你的图表很简单,只有一个数据集,你可以使用data而不是datasets。

labels

x轴的标签集合

options

包含图表选项的对象。 有关可用选项的详细信息,请参阅官方Chart.js文档。

在上面的例子中,我们将图表设置为自适应模式,根据视口大小进行自动调整。

colors

在上面的例子中未显示,但你可以定义自己的颜色, 传入包含以下值的对象文字数组:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选