1. 程式人生 > >Angular ngx-echarts圖表

Angular ngx-echarts圖表

1. 安裝echarts包、ngx-echarts包


npm install echarts --save
npm install ngx-echarts --save

2. angular.json中引入echarts.js檔案


"scripts": [ "node_modules/echarts/dist/echarts.js"  ]

3. 根模組中匯入NgxEchartsModule模組


import {NgxEchartsModule} from 'ngx-echarts';

imports: [ NgxEchartsModule ]

4. 元件中使用echarts圖表

(1). HTML - test.component.html


<div echarts [options]="chartOption" class="demo-chart" style="width: 100%; height: 560px;"></div>

(2). TS - test.compont.ts


export class TestComponent implements OnInit {

    // 定義圖表項
   chartOption: any;

    constructor(private _httpClient: HttpClient){}

   ngOnInit() {
    // 查詢圖表所需資料
    this._httpClient.get('路徑').subscribe((data: any) => {
          //圖表項賦值  
           this.chartOption = {
               color = ['#59a1f8', '#78c87d', '#f6d464', '#445285', '#8e67de', '#e36f7e', '#70c9ca', '#d396c6', '#b09e6c', '#4f58d5', '#96a36f'];
                legend = {};
                tooltip = {};
                dataset = {
                    source: data
                };
                xAxis = {type: 'category'};
                yAxis = {};
                series = [
                    {type: 'bar'}
                ];            
            };

        });

}   

data資料格式:


[

    ["釋出日期","數量"],
    ["2014-03-25",1],
    ["2014-04-04",1],
    ["2014-04-09",1],
    ["2014-04-14",2],
    ["2014-04-17",1]
    ...        

]

5. 重啟程式,瀏覽器訪問:

擴充套件 --------------------

專案中多次用到了柱形圖,配置變數options如何做成通用的??

解決方案:

1. 新增模型檔案 bar.model.ts

// echart- 柱形圖Option
export class BarOptionModel {
    color = ['#59a1f8', '#78c87d', '#f6d464', '#445285', '#8e67de', '#e36f7e', '#70c9ca', '#d396c6', '#b09e6c', '#4f58d5', '#96a36f'];
    legend = {};
    tooltip = {};
    dataset = {
        source: []
    };
    xAxis = {type: 'category'};
    yAxis = {};
    series = [
        {type: 'bar'}
    ];
}

2. 修改test.component.ts如下:

import {BarOptionModel} from '模型檔案';

export class TestComponent implements OnInit {

    // 定義圖表項
   chartOption: BarOptionModel;

    constructor(private _httpClient: HttpClient){}

   ngOnInit() {
    // 查詢圖表所需資料
    this._httpClient.get('路徑').subscribe((data: any) => {
        // 配置圖表項
        this.chartOption = new BarOptionModel();
        // 圖表項中新增資料
        this.chartOption.dataset.source = data;
    });

}