首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角2指令:如何在指令中创建echarts实例?

角2指令:如何在指令中创建echarts实例?
EN

Stack Overflow用户
提问于 2017-02-05 12:19:54
回答 2查看 4.4K关注 0票数 3

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

详细信息

我在ngAfterViewInit()中创建了图表,这是第一次,当窗口调整大小时,图表确实会调整大小。

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

然后单击“回退到图表”页面,重新创建图表,但是,当窗口调整大小时,此时间图表不会调整大小,console.log(chart)返回'undefined'而不是echarts实例。

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

所有代码

下面是EChartsDirective用于ECharts的所有代码:

代码语言:javascript
复制
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();
        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-05 12:23:14

代码语言:javascript
复制
    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();
        }
    }
票数 5
EN

Stack Overflow用户

发布于 2021-03-03 12:23:20

使用ngx-echarts,您可以以更友好的角度在html中这样做:

代码语言:javascript
复制
<div echarts (chartInit)="onChartInit($event)" [options]="options" class="demo-chart"></div>

在你的部分:

代码语言:javascript
复制
onChartInit(e: any) {
    this.chartInstance = e;
    console.log('on chart init:', e);
  }

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42051975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档