【问题标题】:Angular 2 directive: How to get created echarts instance in directive?Angular 2 指令:如何在指令中创建 echarts 实例?
【发布时间】:2017-02-05 12:19:54
【问题描述】:

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


详情

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

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

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

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


所有代码

以下是EChartsEChartsDirective的全部代码:

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

【问题讨论】:

    标签: angular typescript echarts


    【解决方案1】:
        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();
            }
        }
    

    【讨论】:

    • 您好 Günter,感谢您的快速响应! this.myChart.resize(); 得到错误:"Property 'myChart' does not exist on type 'EChartsDirective'",我错过了什么吗?
    • 听起来第一个resize 事件是在ngAfterViewInit() 之前收到的。我更新了我的答案(添加了if(){}
    • 对不起,它有效!你让我今天一整天都感觉很好!非常感谢❤️(顺便说一句,之前因为打错了,我的名字是mychart而不是myChart
    • 不客气。很高兴听到你能让它发挥作用。习惯 - 我总是使用 camelCase - 抱歉。
    • 嗨君特,我的错!我应该使用camelCase。再次,非常感谢!
    【解决方案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

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 1970-01-01
      • 2018-01-17
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 2019-07-06
      相关资源
      最近更新 更多