Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 directive: How to get created echarts instance in directive?

Purpose: I am trying to build a simple Angular 2 directive for ECharts (a chart library)


Details:

I create the charts in ngAfterViewInit(), and for the first time, it works, the charts do resize when window resize.

Then I click to another page, ngOnDestroy() runs, and charts are destroyed.

Then I click back to chart page, charts are re-created, however, this time charts won't resize when window resizes, and console.log(chart) returns 'undefined' instead of echarts instance.

How can I get echarts instance again and make it resizable?


All the code:

Below is all the code of EChartsDirective for ECharts:

import { Directive, ElementRef, Input } from '@angular/core';
let echarts = require('echarts');

@Directive({ selector: '[myECharts]' })

export class EChartsDirective {
    el: ElementRef;
    constructor(el: ElementRef) {
        this.el = el;
    }

    @Input() EChartsOptions: any;
    private mychart;


    ngAfterViewInit() {
        let chart = this.mychart = echarts.init(this.el.nativeElement);

        if (!this.EChartsOptions) return;

        this.mychart.setOption(this.EChartsOptions);

        $(window).on('resize', function(){
            console.log(chart);
            chart.resize(); // <- this only works for the first time
                            // if I change to another page, then back to chart page, it will return 'undefined'
                            // the chart is still there, but won't resize on window resize any more
        })
    }

    ngOnDestroy() {
        if (this.mychart) {
            this.mychart.dispose();
        }
    }
}
like image 706
Alex G Avatar asked Oct 23 '25 15:10

Alex G


1 Answers

    ngAfterViewInit() {
      this.mychart = echarts.init(this.el.nativeElement);
      if (!this.EChartsOptions) return;

      this.mychart.setOption(this.EChartsOptions);
    }

    @HostListener('window:resize)
    onResize() {
        console.log(chart);
        if(this.mychart) {
          this.mychart.resize();
        }
    }
like image 174
Günter Zöchbauer Avatar answered Oct 25 '25 06:10

Günter Zöchbauer