angularchartsapexcharts

Apex chart not working properly with Angular


I'm using https://github.com/apexcharts/ng-apexcharts.

I'm unable to use core ApexCharts methods with the library. Although the readme doc suggest that we can use "appendData" method but when I tried to use in following manner:

chart.component.html

<apx-chart #chartObj></apx-chart>

chart.component.ts

@ViewChild('chartObj',{static: false}) chart: ChartComponent;

method(data){
    this.chart().appendData([{
        data: [Date.now(),data]
      }])
}

I'm getting the error on Chrome console saying: Cannot read property 'appendData' of undefined I have already tried to update using the chart options.

this.chartOptions = {
      series: [
        {
          name: "current",
          data: []
        }
      ],
      chart: {
        type: "line",
        height: 300
      },
      stroke: {
        width: 2,
        curve: "smooth"
      },
      xaxis: {
        type: "datetime"
      }
    };

As I tried to push data to the chart using following code:

this.chartOptions.series[0].data.push([Date.now(),data]);

and also tried this

this.chartOptions.series[0].data.push({x: new Date(),y: data});

Data is inserted only once in the chart if I use it inside ngOnInit. But I want to use this behavior on button click which is not working. Printing the chartOptions on console after the button click, Its updating correctly but this data point is not showing on the chart Please help me out.


Solution

  • I had some problems with Apex Chart too, but some hours later and many cup of cofee, I uderstood a big trap on the example. On the sandbox was used a complex object to fill the data. Ex. let chartOptions = { series: [ name: 'test', data: [...], ... ], chart: {...} };

    Step 1: remove the series from another variable.. public chartOptions = { ... } public _series = [ name: 'test', data: [...], ... ]

    Step 2: Replace the html example with your new variable <apx-chart [series]="chartOptions.series" ... => <apx-chart [series]="_series"

    Step 3: Modify your code to replace the "_series" value this.requestFromMyApi.subscribe( res => this._series = [name: 'test', data: res.map( r => { x: r.date, y: r.value } )] );