Angular 在TypeScript 中使用 ECharts 图表-2

设置方法请看上期“Angular 在TypeScript 中使用 ECharts 图表”。
本文讲解如何把Echarts做成绑定的形式。
1.建一个指令
ng g d NewChart
2.写出指令的代码
import { Directive, Input, ElementRef, OnInit } from '@angular/core';
import * as echarts from 'echarts';

@Directive({
selector: '[appCenterText]'
})
export class NewChartDirective implements OnInit {
afterInit = null; // 这个是初始化完后的

_option = null;
@Input('appCenterText') //一个别名
set Option(value: any) { //做成set get的,便于监测变化而更新图形显示
this._option = value;
if (this.Option && this.afterInit) {
this.afterInit.setOption(this.Option);
}
}

get Option(): any {
return this._option;
}
constructor(
private el: ElementRef
) { }
ngOnInit() {
this.afterInit = echarts.init(this.el.nativeElement); //初始化而已
if (this.Option) {
this.afterInit.setOption(this.Option);
}
}
}

3.使用:
html:



ts代码:

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

lineChartOption = null;
change() {
{
const data = [Math.random() * 20, 2, 6, 3, 2, 9, Math.random() * 10, 3, 4, 8, 4, 5];

  this.lineChartOption = {
    tooltip: {
      trigger: 'axis'
    },
    toolbox: {
      show: true,
    },
    legend: {
      padding: 0
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '新签合同额',
        type: 'line',
        smooth: true,
        itemStyle: {
          normal: {
            lineStyle: {
              color: '#c8c8c8'
            }
          }
        },
        data: [10, 2, 5, 4, 6, 3, 7, 2, 2, 3, 6, 7],
      },
      {
        name: '营业收入',
        type: 'line',
        smooth: true,
        itemStyle: {
          normal: {
            lineStyle: {
              color: '#1ab394'
            }
          }
        },
        data: [3, 2, 4, 7, 0, 3, 1, 3, 4, 1, 2, 3]
      },
      {
        name: '归属母公司净利润',
        type: 'line',
        smooth: true,
        itemStyle: {
          normal: {
            lineStyle: {
              color: '#ff713a'
            }
          }
        },
        data: data
      }
    ]
  };
}

}
}

4.echart其实是属于参数配置型库(基于配置的)。只要把参数配置好,就会根据参数而变化图形。
所以,经过这样的指令的处理,只需要更新配置参数就可以改变图形了,万事大吉。

你可能感兴趣的:(Angular 在TypeScript 中使用 ECharts 图表-2)