Angular 2指令:如何在指令中创建echarts实例?
目的:我正在尝试为ECharts(图表库)构建一个简单的Angular 2指令Angular 2指令:如何在指令中创建echarts实例?,angular,typescript,echarts,Angular,Typescript,Echarts,目的:我正在尝试为ECharts(图表库)构建一个简单的Angular 2指令 详细信息: 我在ngAfterViewInit()中创建图表,它第一次起作用,当窗口调整大小时,图表确实会调整大小 然后我点击另一个页面,ngondestory()运行,图表被销毁 然后我点击返回图表页面,图表被重新创建,然而,这次当窗口调整大小时,图表不会调整大小,console.log(chart)返回'undefined',而不是echarts实例 如何再次获取echarts实例并使其可调整大小 所有代码:
详细信息: 我在
ngAfterViewInit()
中创建图表,它第一次起作用,当窗口调整大小时,图表确实会调整大小
然后我点击另一个页面,ngondestory()
运行,图表被销毁
然后我点击返回图表页面,图表被重新创建,然而,这次当窗口调整大小时,图表不会调整大小,console.log(chart)
返回'undefined'
,而不是echarts实例
如何再次获取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();
}
}
}
import{Directive,ElementRef,Input}来自'@angular/core';
设echart=require(‘echart’);
@指令({选择器:'[myECharts]'})
导出类EChartsDirective{
el:ElementRef;
构造函数(el:ElementRef){
this.el=el;
}
@Input()EChartsOptions:任意;
私人mychart;
ngAfterViewInit(){
让chart=this.mychart=echart.init(this.el.nativeElement);
如果(!this.EChartsOptions)返回;
this.mychart.setOption(this.EChartsOptions);
$(窗口).on('resize',function()){
控制台日志(图表);
chart.resize();//使用ngx echarts,您可以在html中以一种角度更友好的方式执行此操作:
<div echarts (chartInit)="onChartInit($event)" [options]="options" class="demo-chart"></div>
来源:Hi Günter,感谢您的快速响应!this.myChart.resize();
获取错误:“属性'myChart'在'EChartsDirective'类型上不存在”
,我遗漏了什么吗?听起来像是在ngAfterViewInit()
之前收到的第一个resize
事件。我更新了我的答案(添加了if(){}
对不起,这很有效!你让我开心!非常感谢❤️ (顺便说一句,以前,它不工作,因为有一个打字错误,我的名字是mychart
,而不是mychart
)不客气。很高兴听到你能让它工作。习惯-我总是用camelCase-很抱歉。嗨,居里,我的错!我应该用camelCase。再次感谢你!
<div echarts (chartInit)="onChartInit($event)" [options]="options" class="demo-chart"></div>
onChartInit(e: any) {
this.chartInstance = e;
console.log('on chart init:', e);
}