Purpose: I am trying to build a simple Angular 2 directive for ECharts (a chart library)
Details:
I create the charts in ngAfterViewInit(), and for the first time, it works, the charts do resize when window resize.
Then I click to another page, ngOnDestroy() runs, and charts are destroyed.
Then I click back to chart page, charts are re-created, however, this time charts won't resize when window resizes, and console.log(chart) returns 'undefined' instead of echarts instance.
How can I get echarts instance again and make it resizable?
All the code:
Below is all the code of EChartsDirective for 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();
}
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With