NashTech Insights

Implementation of Highcharts in Angular Application: A Comprehensive Guide

Kuldeep
Kuldeep
Table of Contents
Angular HighCharts

Without visually engaging data visualizations, ultramodern web applications would find it far more challenging to convey intricate details to users in a readily approachable and arrestingly visual way. One important tool for creating interactive and visually engaging charts is Highcharts. This blog will walk you through the process of integrating and utilizing Highcharts within an Angular application, using a practical illustration.

Introduction to Highcharts

Highcharts is an important JavaScript charting library that enables us to create interactive and visually engaging charts for web operations. Its features include colorful charts types, customization options, interactivity, and robustness, responsive design, data visualization, exporting and publishing, labeling, high performance, and cross-browser compactivity making it a favored choice for data visualization.
In this blog, we’ll walk you through the process of integrating Highcharts into an Angular application to create a chart that displays population and world share data for the top 20 countries.

Setting Up an Angular Project

Follow these steps to start creating an Angular project and install Highcharts:

  1. Create a New Angular Project:
    • Open a terminal or command prompt.
    • Install the Angular CLI globally if you haven’t already:
      • npm install -g @angular/cli
    • Create a new Angular project:
      • ng new angular-high-chart-demo
    • Navigate into the project directory:
      • cd angular-high-chart-demo
  2. Install Highcharts via npm:
    • npm install Highcharts

With these steps, you have set up a new Angular project and installed Highcharts, making it available for use within your application.

Creating a Chart Component

Let’s create a ‘DemoChartComponent’: ng g c demo-chart
The DemoChartComponent is an Angular component responsible for displaying population and world share data using Highcharts. It subscribes to the PopulationService to fetch data, transforms it into a suitable format, and renders the data as a column chart and a spline line chart.

Fetching Data Using a Service

In the context of our application, the PopulationService is responsible for interacting with external data sources, such as APIs or databases, to gather the necessary population data. By utilizing Angular’s built-in HttpClient module, the service can efficiently make HTTP
requests to recoup this data.

import { Injectable } from '@angular/core';
import {Observable} from "rxjs";
import {HttpClient} from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class PopulationService {

  // URL to the Data Source
  private dataUrl = '/assets/population.json';

  constructor(private http: HttpClient) { }

  getPopulationData(): Observable<any[]> {
	  // Fetch population data using HttpClient
    return this.http.get<any[]>(this.dataUrl);
  }
}

The PopulationService is injected into the DemoChartComponent, allowing the component to call the getPopulationData method and subscribe to the data stream.

this.populationService.getPopulationData().subscribe()

Transforming Data for the Chart

To create the Highcharts chart, you need to transform the fetched data into a format suitable for visualization. In this example, you map the population and world share data into arrays of objects with the required properties.

// DemoChartComponent
// Subscribe to population data from a service
this.populationDataSubscription$ = this.populationService.getPopulationData().subscribe(data => {

  // Transforming population data for column chart
  const chartData = data.map(item => ({
    name: item.Country,
    y: parseInt(item.Population.replace(/,/g, '')),
    countryInfo: item.Country,
    populationInfo: item.Population,
    netChangeInfo: item.NetChange,
    worldSharePercent: parseFloat(item.WorldShare.replace('%', ''))
  }));

  // Transforming world share data for the line chart
  const lineSeriesData = chartData.map(item => ({
    name: item.name,
    y: item.worldSharePercent,
    country: item.countryInfo
  }));

Here, the chartData array is created by mapping each data item to an object with properties like name and y (value) for the column chart. Similarly, the lineSeriesData array is created for the line chart. We will use these transformed data arrays to populate the series of the Highcharts chart.

Configuring the HighCharts

Now that we have fetched and transformed our data, it’s time to create a Highcharts chart to visualize it. In this step, we’ll delve into configuring the chart’s appearance, axes, legends, and tooltips.
Highcharts Configuration Options
Highcharts charts are highly customizable, and you can control various aspects of their appearance and behavior through configuration options. Let’s look at some of the key options used in our example:

  • chart: Specifies the general chart settings, such as its type (e.g., column, line) and other attributes.
  • title: Sets the chart’s title.
  • xAxis and yAxis: Configure the X and Y axes, including their titles, labels, and other properties.
  • legend: Controls the visibility and positioning of the legend.
  • tooltip: Configures the appearance and content of tooltips when hovering over data points.
  • series: It defines the data series to plot on the chart.
  • plotOptions: Specifies various plot options for different chart types, such as column width and line styles.
// Create a Highcharts chart
Highcharts.chart('chartContainer', {
  // Chart type configurations
  chart: {
    type: 'column'
  },
  // Title configurations
  title: {
    text: 'Population and World Share by top 20 Countries'
  },
  // X-axis configurations
  xAxis: {
    type: 'category',
    labels: {
      style: {
        fontSize: '13px',
        fontFamily: 'Arial, sans-serif'
      }
    },
    crosshair: true,
  },
  //  Y-axis configurations
  yAxis: [
    // Left Y-axis
    {
      title: {
        text: 'Population'
      }
    },
    // Right Y-axis
    {
      title: {
        text: 'World Share (%)'
      },
      opposite: true
    }
  ],
  // Chart legend configurations
  legend: {
    enabled: true
  },
  // Chart tooltip configurations (Global)
  tooltip: {
		// Tool-tip
      },
  // Series configurations
  series: [
    // Series configurations for column chart
      ],
  // Plot options for column and line chart
  plotOptions: {
    column: {
      pointPadding: 0.2,
      borderRadius: 0,
      pointWidth: 30,
      color: "#4472c4",
    },
    spline: {
      lineWidth: 2,
      color: "#ed7d31",
    },
  }

Creating the Chart – Column and Line

In this step, we actually create the Highcharts chart by using the Highcharts.chart method. We pass in a configuration object that defines the chart’s appearance and data. The chart is created inside the ngOnInit method using the fetched and transformed data. Our example includes two series: a column chart for population data and a spline line chart for world share percentages.

// Series configurations
series: [
  // Series configurations for column chart
  {
    name: 'Population',
    type: 'column',
    data: chartData,
    yAxis: 0,
  },
  // Series configurations for line chart
  {
    name: 'World Share (%)',
    type: 'spline',
    data: lineSeriesData,
    yAxis: 1,
    dataLabels: {
      enabled: true,
      format: '{y}%',
    },
    // Tooltip content formatting for the line series
    tooltip: {
      headerFormat: '<table>',
      pointFormat: '<tr><td style="color:#666666; padding:3px; font-size:13px;">Country: </td>'
        + '<td style="color:#333333; font-size:13px; padding-left:20px;text-align: right;"><b>{point.country}</b></td></tr>'
        + '<tr><td style="color:#666666; padding:3px; font-size:13px;">% World\'s share: </td>'
        + '<td style="color:#333333; font-size:13px; padding-left:20px;text-align: right;"><b>{point.y}%</b></td></tr>',
      footerFormat: '</table>',
      shared: false,
      useHTML: true,
    },
  },
],

Cleaning Up and Preventing Memory Leaks

Angular components may hold onto subscriptions even after they are no longer needed, leading to memory leaks. To avoid this, we use the ngOnDestroy lifecycle hook to unsubscribe from the data subscription. This action ensures that the component’s destruction terminates/ends the subscription, thereby freeing up resources.

ngOnDestroy() {
  // Unsubscribe from the population data subscription when the component is destroyed
  if (this.populationDataSubscription$) {
    this.populationDataSubscription$.unsubscribe();
  }
}

Testing Highcharts in Angular

To ensure the functionality and reliability of the DemoChartComponent, we can write test cases using Angular’s testing utilities. This involves creating mock services, simulating component behaviour, and asserting expected outcomes. Detailed test cases can validate the creation of the chart, the fetching of data, and the correct management of subscriptions.

To test components using the UI, you can indeed run your Angular application using ng serve and access it at localhost:4200.

This is What UI looks like:

HighCharts in Angular UI

Conclusion

By following the way outlined in this blog, you’ve successfully integrated Highcharts into your Angular application to produce visually charming and interactive charts. You have acquired the skills to establish the project, retrieve and transform data, customize the chart’s appearance, handle subscriptions, and create tests to guarantee the proper functioning of the chart.

To sum it up, Highcharts stands out as a crucial tool that elevates data visualization within Angular applications. It empowers you to craft informative and captivating charts, providing valuable insights to users.

Visit Official site for more information related to HighCharts.

Kuldeep

Kuldeep

An expert-level Java Consultant with experience building large-scale, loosely coupled, state-of-the-art enterprise applications. Excellent experience in writing microservices, building integration applications, and working on SAAS-based applications. Strong focus on creating a positive working environment and gaining valuable insights.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: