3

目的:我正在尝试为 ECharts(图表库)构建一个简单的 Angular 2 指令


详情

我在 中创建图表ngAfterViewInit(),并且第一次,它可以工作,当窗口调整大小时图表会调整大小。

然后我点击到另一个页面,ngOnDestroy()运行,图表被销毁。

然后我点击返回图表页面,重新创建图表,但是,这次图表不会在窗口调整大小时调整大小,而是console.log(chart)返回'undefined'而不是 echarts 实例。

如何再次获取 echarts 实例并使其可调整大小?


所有代码

以下是EChartsDirectiveECharts 的所有代码:

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();
        }
    }
}
4

2 回答 2

5
    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();
        }
    }
于 2017-02-05T12:23:14.177 回答
2

使用 ngx-echarts,您可以在 html 中以更 Angular 友好的方式进行操作:

<div echarts (chartInit)="onChartInit($event)" [options]="options" class="demo-chart"></div>

并在您的组件中:

onChartInit(e: any) {
    this.chartInstance = e;
    console.log('on chart init:', e);
  }

来源:https ://xieziyu.github.io/ngx-echarts/#/basic/basic-usage

于 2021-03-03T12:23:20.143 回答