百度的ECharts圖表插件很強(qiáng)大蒋得,完美支持移動端肆捕,github也一直有專人維護(hù)颖变,很不錯掌实。
1.安裝ECharts
用npm安裝ECharts:
npm install echarts --save
npm install @types/echarts --save
2.使用ECharts
頁面引入import ECharts from 'echarts';
需要在ion-content內(nèi)放一個div陪蜻,作為圖表的容器:
<div id="main" style="width: 350px;height:300px;" ></div>
在頁面的ts文件里的ionViewDidLoad
方法里:
var myChart = ECharts.init(document.getElementById('main') as HTMLDivElement);
// 指定圖表的配置項和數(shù)據(jù)
var option = {
title: {
text: 'ECharts 入門示例'
},
tooltip: {},
legend: {
data: ['銷量']
},
xAxis: {
data: ["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]
},
yAxis: {},
series: [{
name: '銷量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 使用剛指定的配置項和數(shù)據(jù)顯示圖表。
myChart.setOption(option);
更推薦如下這種angular操作dom的方式
1.在頁面html
<div #salesBarChart style="height:300px;margin: 10px;"></div>
2.在ts文件
import {ElementRef, ViewChild} from '@angular/core';
...
@ViewChild('salesBarChart') salesBarChart: ElementRef;
...
ionViewDidLoad() {
let myChart=ECharts.init(this.salesBarChart.nativeElement);
.....//同上
}
3.網(wǎng)上找的自適應(yīng)方法
在src目錄下添加directives目錄贱鼻,添加一個auto-fit-layout.ts文件宴卖,輸入以下代碼:
import { Directive, ElementRef, Renderer } from '@angular/core';
@Directive({
selector: '[my-auto-fit-layout]'
})
export class AutoFitLayout {
constructor(public element: ElementRef, public renderer: Renderer) {
//因為ionic的默認(rèn)padding寬度是16
renderer.setElementStyle(element.nativeElement, 'width', `${(document.body.clientWidth - 32).toString()}px`);
}
}
使用這個指令時,會獲取當(dāng)前窗口寬度邻悬,并設(shè)置指定div的寬度症昏。將這個指令應(yīng)用到圖表的容器上:
<!-- 為ECharts準(zhǔn)備一個具備大小(寬高)的Dom -->
<div id="main" style="width: 350px;height:300px;" my-auto-fit-layout></div>
這樣就可以在生成圖表的時候自動適應(yīng)當(dāng)前容器的寬度了父丰。