angular 封装一个简易版本 vue-echarts 组件

410 阅读1分钟

用过vue-echarts的都知道,使用的时候只需要把options传入组件就能够实现了,使用起来特别的方便.

image.png

image.png

因为项目使用的是angular,并没有类似的组件.因此参考vue-echarts了,封装了一个简易版本的angular组件.

draw-echarts.component.ts

/*
 * @Description: echarts通用组件(传入options,父组件必须设置宽高)
 */
import { Component, AfterViewInit, OnChanges, Input, SimpleChange } from '@angular/core';
import { v4 as uuidv4 } from 'uuid';
import * as echarts from 'echarts';
// import 'echarts-liquidfill';

@Component({
  selector: 'app-draw-echarts',
  templateUrl: './draw-echarts.component.html',
  styleUrls: ['./draw-echarts.component.scss']
})
export class DrawEchartsComponent implements AfterViewInit, OnChanges {
  @Input() options; // 配置
  @Input() theme; // 主题
  echartsId = `echarts${uuidv4()}`; // 自动生成id
  dom: HTMLElement; // 获取的dom
  chart; // echart实例

  ngAfterViewInit() {
    this.initChart();
  }

  initChart() {
    window.requestAnimationFrame(() => {
      if (!this.chart) {
        this.dom = document.getElementById(this.echartsId);
        this.chart = echarts.init(this.dom, this.theme);
      }
      if (this.options) {
        this.chart.clear();
        this.chart.setOption(this.options);
      }
    });
  }
  ngOnChanges(changes) {
    const options: SimpleChange = changes.options;
    if (options && !options.firstChange) { // 配置项改变
      this.initChart();
    }
  }
}

draw-echarts.component.scss

.echarts {
    width: 100%;
    height: 100%;
}

draw-echarts.component.html

<div class="echarts" [id]="echartsId">
</div>
  • 使用

image.png

传入options

image.png

成功实现 image.png

喜欢的点点赞哦~