原文連結:這裡
0.前言
項目中最近要使用echarts做那種看起來高大上的圖。于是搞起了echarts。本文主要介紹angualr中如何使用echarts。
anuglar CLI 11.5
1.建立angular項目
建立項目參考:angular從0到1:環境安裝及運作 – 每天進步一點點 (longkui.site)
2.引入echarts
我們安裝echarts,使用下面兩個指令。
npm install echarts --save (yarn add echarts)
npm install ngx-echarts --save (yarn add ngx-echarts)
然後我們在package.json(有兩個,最外層那個)中可以看到我們剛才安裝的echarts。
然後找到angular.json。找到build/options中。
然後在scripts中添加下面的這段代碼:
“node_modules/echarts/dist/echarts.js”
然後我們在app.module.ts中使用引入echarts(實際開發中,自己建立一個module,同樣的操作引入)。
導入:
import { NgxEchartsModule } from ‘ngx-echarts’;
imports: [
…
NgxEchartsModule
],
然後我們打開app.component.html檔案。
測試圖表 然後我們打開Echarts 的執行個體。
Examples – Apache ECharts
option = {
xAxis: {
type: ‘category’,
data: [‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’, ‘Sun’]
},
yAxis: {
type: ‘value’
},
series: [{
data: [120, 200, 150, 80, 70, 110, 130],
type: ‘bar’,
showBackground: true,
backgroundStyle: {
color: ‘rgba(180, 180, 180, 0.2)’
}
}]};
我們在app.component.ts 添加如下代碼
import { Component, OnInit } from ‘@angular/core’;
import * as echarts from ‘echarts’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [’./app.component.less’]
})
export class AppComponent implements OnInit {
title = ‘myapp’;
ngOnInit() {
this.initChart()
}
initChart() {
var chartDom = document.getElementById(‘testchart’);
var myChart = echarts.init(chartDom);
var option;
option = {
xAxis: {
type: ‘category’,
data: [‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’, ‘Sun’]
},
yAxis: {
type: ‘value’
},
series: [{
data: [120, 200, 150, 80, 70, 110, 130],
type: ‘bar’,
showBackground: true,
backgroundStyle: {
color: ‘rgba(180, 180, 180, 0.2)’
}
}]
};
option && myChart.setOption(option);
}
}
如果報錯:ERROR in The target entry-point “ngx-echarts” has missing dependencies:@juggle/resize-observer。請點選這裡解決。
然後執行 ng serve