Rajan Sharma
Rajan Sharma

Reputation: 485

HighCharts angular not working with dynamic data from Angular service

Trying to assign dynamic values coming from angular service in angular component does not update HighChart. If I call drawChart from outside of service response subscribe method, it works but with hardcoded data because response data is not available outside subscribe method.

  1. Following are HighChart options.

        chart:{ type: "bar"},
        title: {text:null},
        xAxis:{categories:null},
        yAxis: {
          title:{
            text:"time (seconds)"
          }
        },
        tooltip: {
          valueSuffix:"seconds"
        },
        series: []
         };```
    
    
  2. HighChart on my HTML.

        [Highcharts] = "SomeChart"
        [options] = "ChartOptions"
        style = "width: 100%; height: 100%; display: block;">
       </highcharts-chart>```
    
    
  3. This high chart is being populated by following code in angular component.

        let resp = this.RptService.getWorkflowAvgTime();
        resp.subscribe(reportData=> {this.DataSource.data = reportData as sommeObject[];
        this.drawChart(reportData);})
      }```
    
    
  4. following is drawChart function

        {
            let s: Array<any> = []
            data.forEach(function (obj)
        {
             s.push({name: obj.yIdentifier, data:[obj.value]})
        })
    
           this.ChartOptions.series= s;
           console.log(this.ChartOptions.series); // Console prints proper values assigned to chartOptions 
        }```
    
    
    
    

Upvotes: 0

Views: 2539

Answers (1)

Mateusz Kornecki
Mateusz Kornecki

Reputation: 775

It is not working because to perform an update using the highcharts-angular you need to mark it by toggling the updateFlag. Without that, you will mutate the chartOptions but your chart will not update itself.

Docs references:
https://github.com/highcharts/highcharts-angular#options-details

Live demo:
https://stackblitz.com/edit/highcharts-angular-optimal-way-to-update-c9zk9y?file=src/app/app.component.ts

<highcharts-chart 
   [Highcharts]="Highcharts"
   [options]="chartOptions"
   [(update)]="updateFlag"
>
</highcharts-chart>

<button (click)="handleUpdate()">Update chart</button>
export class AppComponent  {
   Highcharts: typeof Highcharts = Highcharts;
  updateFlag = false;

  data = [1, 2, 3, 4];

  chartOptions: Options = {
    series: [
      {
        type: 'line',
        data: this.data
      }
    ]
  }


  handleUpdate() {
    this.chartOptions.title =  {
      text: 'updated'
    };

    this.chartOptions.series[0] = {
      type: 'line',
      data: [5, 4, 3, 2, 1]
    }

    this.updateFlag = true;
  }
}

Upvotes: 2

Related Questions