Is it possible to use ECharts Baidu with Angular 2 and TypeScript

Anton Cholakov picture Anton Cholakov · Jul 2, 2016 · Viewed 13.2k times · Source

I am trying to implement EChart Baidu in Angular 2 application (typescript).

I am following the start guide on their website https://ecomfe.github.io/echarts/doc/start-en.html but have no idea how I am supposed to init the chart having no clue about the function parameter of this line of code:

function (ec) {
            var myChart = ec.init(document.getElementById('main')); 

Using Angular 2 I have ngOnInit() function that can be used as jquery's $(document).ready().

I've tries to implement ECharts in a separate page using pure javasript and is working just fine. I even have HTML theme Limitless.

The problem is that I don't know how to get this 'ec' parameter from the code above in Angular2.

Any help would be appreciated! Thank you

Answer

TossPig picture TossPig · Feb 9, 2017
npm install --save echarts
npm install --save-dev @types/echarts

code:

import {
  Directive, ElementRef, Input, OnInit, HostBinding, OnChanges, OnDestroy
} from '@angular/core';

import {Subject, Subscription} from "rxjs";

import * as echarts from 'echarts';
import ECharts = echarts.ECharts;
import EChartOption = echarts.EChartOption;


@Directive({
  selector: '[ts-chart]',
})
export class echartsDirective implements OnChanges,OnInit,OnDestroy {
  private chart: ECharts;
  private sizeCheckInterval = null;
  private reSize$ = new Subject<string>();
  private onResize: Subscription;

  @Input('ts-chart') options: EChartOption;

  @HostBinding('style.height.px')
  elHeight: number;

  constructor(private el: ElementRef) {
    this.chart = echarts.init(this.el.nativeElement, 'vintage');
  }


  ngOnChanges(changes) {
    if (this.options) {
      this.chart.setOption(this.options);
    }
  }

  ngOnInit() {
    this.sizeCheckInterval = setInterval(() => {
      this.reSize$.next(`${this.el.nativeElement.offsetWidth}:${this.el.nativeElement.offsetHeight}`)
    }, 100);
    this.onResize = this.reSize$
      .distinctUntilChanged()
      .subscribe((_) => this.chart.resize());

    this.elHeight = this.el.nativeElement.offsetHeight;
    if (this.elHeight < 300) {
      this.elHeight = 300;
    }
  }


  ngOnDestroy() {
    if (this.sizeCheckInterval) {
      clearInterval(this.sizeCheckInterval);
    }
    this.reSize$.complete();
    if (this.onResize) {
      this.onResize.unsubscribe();
    }
  }
}

luck :)