# Ionic 整合 Echarts
本文主要介绍如何在 Ionic 项目中使用 Echarts 来绘制图表。
本文书写时使用软件版本ionic@6.12.0
angular/cli@10.0.5
ngx-echarts@5.2.1
# 安装
# if you use npm | |
npm install echarts -S | |
npm install ngx-echarts -S | |
npm install resize-observer-polyfill -D | |
# or if you use yarn | |
yarn add echarts | |
yarn add ngx-echarts | |
yarn add -D resize-observer-polyfill |
# 配置对应文件
修改 app.module.ts
文件,导入 NgxEchartsModule
import { NgxEchartsModule } from 'ngx-echarts'; | |
@NgModule({ | |
imports: [ | |
NgxEchartsModule.forRoot({ | |
/** | |
* This will import all modules from echarts. | |
* If you only need custom modules, | |
* please refer to [Custom Build] section. | |
*/ | |
echarts: () => import('echarts'), // or import('./path-to-my-custom-echarts') | |
}), | |
], | |
}) | |
export class AppModule {} |
# 使用说明
HTML 模板文件
<div echarts [options]="chartOption" class="demo-chart"></div> |
对应组件内部添加控制参数
chartOption: EChartOption = { | |
xAxis: { | |
type: 'category', | |
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], | |
}, | |
yAxis: { | |
type: 'value', | |
}, | |
series: [ | |
{ | |
data: [820, 932, 901, 934, 1290, 1330, 1320], | |
type: 'line', | |
}, | |
], | |
}; |
# 插件使用
ngx-echarts 支持 echarts 的插件和主题,例如我就需要用到水滴图,所以需要 echarts-liquidfill
插件
使用如下,在导入 echarts
后导入需要插件和主题。
... | |
import * as echarts from 'echarts'; | |
import "echarts-liquidfill/dist/echarts-liquidfill.min.js"; | |
... |
# 优化
你可以选择导入一部分需要使用的图表类型来减少应用体积,这一部分需要使用到 custom-echarts
导入文件,具体可以参考官方的 ngx-echarts
说明进行删减。
# FAQs:
Q: 报错 Required resize-observer-polyfill
'
A: 安装对应包即可 npm i resize-observer-polyfill --save
Q: 报错 Can't bind to 'options' since it isn't a known property of 'div'.
A: 在对应组件的 module.ts
中 import NgxEchartsModule
, 你也可以把这个模块写入 shareModule 中直接导入
# 相关链接
Ngx-Echarts
Echarts 官网