国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > 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

在上面的例子中未顯示,但你可以定義自己的顏色, 傳入包含以下值的對象文字數組:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 福建省| 洛川县| 容城县| 天等县| 普兰县| 庐江县| 合山市| 淮滨县| 清新县| 施秉县| 伊吾县| 南丰县| 泰来县| 辛集市| 陆河县| 拉萨市| 墨玉县| 台山市| 塔城市| 武山县| 中方县| 临洮县| 庆城县| 奈曼旗| 郧西县| 江油市| 施甸县| 乌鲁木齐市| 清水河县| 安泽县| 丰宁| 富源县| 增城市| 阿克陶县| 个旧市| 武义县| 常宁市| 楚雄市| 巫溪县| 博爱县| 钟祥市|