2017-02-05 4 views
1

목적 : 나는 ECharts에 대한 간단한 각도 2 지시자 (차트 라이브러리)각도 2 지시문 : 지시문에서 생성 된 echarts 인스턴스를 얻는 방법?


세부 구축을 위해 노력하고있다 :

내가 ngAfterViewInit()에서 차트를 만드는, 그리고 처음으로 , 그것은 작동, 차트 크기를 조정할 때 창 크기를 조정합니다.

다른 페이지로 이동하면 ngOnDestroy()이 실행되고 차트가 삭제됩니다.

차트 페이지로 다시 돌아오고 차트가 다시 생성되지만이 시간 차트의 크기가 조정되지 않을 때 console.log(chart)은 echarts 인스턴스 대신 'undefined'을 반환합니다.

echarts 인스턴스를 다시 가져 와서 크기를 조정하려면 어떻게해야합니까?


모든 코드 :

아래 ECharts에 대한 EChartsDirective의 모든 코드 : 빠른 응답

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();'오류가 발생했습니다 : ' "myChart'속성이 'EChartsDirective'유형에 존재하지 않습니다." –

+0

첫 번째'resize' 이벤트와 같은 소리가'ngAfterViewInit()'전에 수신되었습니다. 나는 나의 대답을 업데이트했다. (덧붙여'if() {}' –

+1

미안하다, 일한다! 내 날을 만들었다! 정말 고마워요 (BTW, 이전에는 오타가 있었기 때문에 작동하지 않았습니다, 제 이름은'mychart 'myChart' 대신에) –