Purpose: I am trying to build a simple Angular 2 directive for ECharts (a chart library)
ngAfterViewInit()
ngOnDestroy()
console.log(chart)
'undefined'
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();
}
}
}
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();
}
}