twp0217 / ngx-echarts

Apache ECharts component for Angular(基于 Angular 的 Apache ECharts 组件)
https://twp0217.github.io/ngx-echarts/
82 stars 25 forks source link

TypeError: _this.chart is undefined 报错 #32

Closed yuantingfei closed 6 years ago

yuantingfei commented 6 years ago

html :<echarts-ng2 [style]="{'width': '100%', 'height': '600px'}" #myEcharts>

ts: @ViewChild('myEcharts') public echarts: ECharts; ngOnInit() {
this.echarts.setOption(this.option, true);//这里报错 }

option也定义了的 不知道为啥这里报错,只要调用this.echarts的方法都报错

yuantingfei commented 6 years ago

代码漏了
<echarts-ng2 [style]="{'width': '100%', 'height': '600px'}" #myEcharts>这里有闭合的

twp0217 commented 6 years ago

<echarts-ng2 [option]="option"></echarts-ng2> option直接传入

yuantingfei commented 6 years ago

但是我怎么加事件呢?

twp0217 commented 6 years ago
this.echarts.on('click', (params: Object) => {
  console.log(params);
});

https://twp0217.github.io/echarts-ng2/#/

yuantingfei commented 6 years ago

不知道为啥 就是这样会报TypeError: _this.chart is undefined

yuantingfei commented 6 years ago

我感觉是echarts没有初始化,但是按照例子@ViewChild('myEcharts') public echarts: ECharts;这行应该就行了呀???

twp0217 commented 6 years ago

html

<echarts-ng2 #echarts [option]="option"></echarts-ng2>

<div class="row">
    <div class="col-md-12">
        <a class="btn btn-primary" (click)="onEvent()">绑定点击事件</a>
        <a class="btn btn-primary" (click)="offEvent()">解除点击事件</a>
    </div>
</div>

ts

import { Component, ViewChild } from '@angular/core';

import { EChartOption, ECharts } from 'echarts-ng2';

@Component({
    selector: 'method-charts',
    templateUrl: 'method.component.html'
})
export class MethodComponent {
    @ViewChild('echarts') echarts: ECharts;
    option: EChartOption = {
        title: {
            text: 'ECharts 入门示例'
        },
        tooltip: {},
        legend: {
            data: ['销量']
        },
        xAxis: {
            data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
        },
        yAxis: {},
        series: [{
            name: '销量',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
        }]
    };

    onEvent() {
        this.echarts.on('click', (params: Object) => {
            console.log(params);
        });
    }
    offEvent() {
        this.echarts.off('click');
    }
}

按照这个试试

yuantingfei commented 6 years ago

我知道原因了 应该在组件的生命钩子ngAfterViewInit中执行 不然会报这个错误 现在解决了 谢谢了