title: Angular 2 directive: How to get created echarts instance in directive?
body: <p><strong>Purpose</strong>: I am trying to build a simple Angular 2 directive for ECharts (a chart library)</p>
  
  <hr>
  
  <p><strong>Details</strong>:</p>
  
  <p>I create the charts in <code>ngAfterViewInit()</code>, and for the first time, it works, the charts do resize when window resize.</p>
  
  <p>Then I click to another page, <code>ngOnDestroy()</code> runs, and charts are destroyed.</p>
  
  <p>Then I click back to chart page, charts are re-created, however, this time charts won't resize when window resizes, and <code>console.log(chart)</code> returns <code>'undefined'</code> instead of echarts instance. </p>
  
  <p>How can I get echarts instance again and make it resizable?</p>
  
  <hr>
  
  <p><strong>All the code</strong>:</p>
  
  <p>Below is all the code of <code>EChartsDirective</code> for ECharts:</p>
  
  <pre><code>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(); // &lt;- 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();
          }
      }
  }
  </code></pre>