Getting the chart instance using Highcharts Angular

May 03, 2022

Have you ever worked with Highcharts? If so, you may have found that getting the instance of a chart isn’t as straightforward as it should be. Fortunately, the highcharts-angular library makes this pretty easy for us.

In my Word Traverse project I am using a packed bubble chart type to display some data. I recently found myself needing to get the instance of the chart so I could update the series color and series text color when the theme of the application is changed. I’ve worked with Highcharts before and remembered having to dig around to figure out how I could get the instance of the chart. Let’s face it, Highcharts is a powerful library but it can be challenging to use. I was able to find in the highcharts-angular readme an entry on how to get the chart instance. I’ll show you how I did it.

The template for my chart looks like this:

    <highcharts-chart
      [Highcharts]="Highcharts"
      [options]="chartOptions"
      (chartInstance)="onChartInstance($event)"
      style="width: 100%; height: 100%; display: block"
    ></highcharts-chart>

As you can see, there’s an event called chartInstance that is emitted after the chart is created. The event returns the chart instance.

The onChartInstance method looks like this:

  onChartInstance(chart: Highcharts.Chart) {
    this.chart = chart;
    this.updateChartBackground();
  }

I am setting the component’s chart property to the emitted chart. Now I have access to the chart. Super easy!

And here is what I’m doing once I get the chart instance:

private updateChartBackground() {
    this.chart.update({
      chart: {
        backgroundColor: this.theme.background,
      },
      plotOptions: {
        packedbubble: {
          color: this.theme.secondary,
          dataLabels: {
            color: this.theme.bubbleTextColor,
          },
        },
      },
    });
  }

Now that I have access to the chart I can easily call update on the chart and pass in the properties that I want to update.

Working with Highcharts can be challenging. I do hope that this quick blurb on getting the chart instance will be useful to someone out there. I’ll probably publish more content on Highcharts in the future. If there’s anything specific that you’d like me to cover, just shoot me a message and if it’s something I feel like I can cover, I’ll do it.

Thanks!


Profile picture

Written by Jason Fritsche.

Designed and built by Jason Fritsche