Search code examples
angulartypescripthighchartsangular-highcharts

Angular 7 - Dynamic HighChart update


In my angular solution I need to display some charts using Highcharts. In my component.ts I have the following code:

import * as Highcharts from "highcharts";

highcharts = Highcharts;
  chartOptions = {
    chart: {
       type: "spline",
       title: "Reach/TRP"
    },
    xAxis: {
      title: {
        text: this.xAxis.name
      }
    },
    yAxis: {
       title: {
          text: "Reach"
       }
    },
    series: [
       {
          name: this.xAxis.name,
          data: this.xAxis.data
       }
    ]
 };

Then in my .html I use it like this:

<highcharts-chart
  [Highcharts] = "highcharts"
  [options] = "chartOptions"
  style="width: 100%; height: 400px; display: block;">
</highcharts-chart>

On my html I also have the following dropdown:

<p-dropdown [showTransitionOptions]="'0ms'" [hideTransitionOptions]="'0ms'"
  dropdownIcon="fa fa-angle-down" class= "nextgen-dropdown" 
  [options]="optionsLookup"
  [(ngModel)]="selectedOption" (onChange)= "onOptionChange($event)">
</p-dropdown>

Which have the "OnOptionChange" method that should update the Chart like this:

 onOptionChange() {
    this.xAxis.name = this.selectedOption;
    this.xAxis.data = [100, 100, 200, 200, 350, 250];
    this.chartOptions.series[0] = this.xAxis;
  }

The problem here is that the method is correctly invoked but the chart is not updated at all.

What I'm missing here?


Solution

  • You should pass new options reference:

    onOptionChange() {
      this.xAxis.name = this.selectedOption;
      this.xAxis.data = [100, 100, 200, 200, 350, 250];
      this.chartOptions.series[0] = this.xAxis;
    
      this.chartOptions = { ...this.chartOptions }; // this should do the trick
    }