2017-02-05 66 views
1

目的:我想建立一个简单的角度2指令的ECharts(图表库)Angular 2指令:如何在指令中创建echarts实例?


详细

ngAfterViewInit()创建图表,并首次,它可以工作,图表在调整窗口大小时会调整大小。

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

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

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


所有代码

下面是EChartsDirective为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(); 
     } 
    } 
} 

回答

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

喜君特,感谢的快速响应! 'this.myChart.resize();'获取错误:'“Property'myChart'在类型'EChartsDirective'”'上不存在,我错过了什么? –

+0

在'ngAfterViewInit()'之前收到了第一个'resize'事件的声音。我更新了我的答案(添加了'if(){}' –

+1

对不起,它工作!你做了我的一天!非常感谢你❤️(顺便说一句,它不工作,因为有一个错字,我的名字是'mychart ''而不是'myChart') –