Setting up a chart in an Ionic App using Highcharts

IONIC Highcharts tutorial

 

For native iOS apps, check out the new Highcharts iOS wrapper.

Ionic has grown spectacularly in the last two years; from using AngularJS initially to Angular 4 and now TypeScript in Ionic Framework (version 3). I am a big fan of Ionic.

My other favorite JavaScript library is Highcharts (no surprise there). Like most Highcharts fans, I love how easy it is to create responsive and interactive charts. That is why I decided to set up a project to combine my two favorite libraries. Will it blend? Let’s give it a shot!

First thing first: install Ionic by typing the following commands in the command prompt or terminal. Actually, the first thing is to install the latest version of NodeJs, if you haven’t done so already. Download NodeJS from nodejs.org.
npm install ionic -g
npm install cordova -g

Install also Cordova as Ionic Apps require Cordova. (Ok, this is technically the second first thing to do…)
Cordova wraps your HTML, SCSS, and TS based Web App into a Native Android or iOS App, which is often a good option.
Finally, let’s create our first Ionic App:
ionic start blank
Replace with the name of your choice to create an app. For this article, I use the name HighChartsIonic. “blank” is a template name to create a blank Ionic App with minimal pre-written code.
ionic start HighChartsIonic

Once this command finishes its execution, a new folder with the name HighChartsIonic is created. Open that folder in the text editor of your choice; I use VS Code as a text editor, as it allows me to run the app in the browser. (You may naturally use any other IDE of your choice). Open the terminal from the view menu or press Ctrl + ` (backtick) and write the following command:
ionic serve

This command builds and launches the app in the browser. To get a more mobile-like view in the browser use –l flag to launch the app in the lab mode.
ionic serve –l

At this point of the project you should see something like this in the browser:

This is a preview of how the application will look like on a real mobile device. Let’s bring in Highcharts and create a chart on this page. Get back to VS Code, and in the terminal press Ctrl + C to stop the Ionic Development Server. Type in the following commands to install Highcharts.
npm install highcharts –save

The result will look like:

The message on the screen is information that Highcharts module has been installed successfully (notice the text in this color).
Open the file ./src/pages/home/home.html and replace everything inside the ion-content tag with a div like this.

<div id="container" style="display: block;"	></div>

This div is a container to hold the chart. I write the code in home.ts file. The home.html and home.ts are the files in charge of creating the home page in the app.
In home.ts, on the top, import the highcharts module first.

import * as HighCharts from 'highcharts';

Next, create a function called ionViewDidLoad() inside the HomePage class, just after the constructor. The file should look like this:

import {
  Component
} from '@angular/core';
import {
  NavController
} from 'ionic-angular';
import * as HighCharts from 'highcharts';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {}

  ionViewDidLoad() {}
}

The ionViewDidLoad is a special function which is executed after the View has been initialized and loaded; this makes sure to avoid any errors during the components’ access in the view. Create a new HighCharts.chart object in the ionViewDidLoad:

var myChart = HighCharts.chart('container', {
  chart: {
    type: 'bar'
  },
  title: {
    text: 'Fruit Consumption'
  },
  xAxis: {
    categories: ['Apples', 'Bananas', 'Oranges']
  },
  yAxis: {
    title: {
      text: 'Fruit eaten'
    }
  },
  series: [{
    name: 'Jane',
    data: [1, 0, 4]
  }, {
    name: 'John',
    data: [5, 7, 3]
  }]
});

 

Save the file, and in the terminal type ionic serve –l to run the app in the browser in the lab mode. The app should look like this:

The charts are now visible on the homepage of the Ionic 3 App. Let’s play around with the chart object a little bit and see how it modifies the charts in the app.
Change the chart.type property in the JSON object to a line and save the file. The browser will reload the app in a few seconds as soon as the file is saved. The result should look like:

Awesome, isn’t it? Let’s try one more thing. Change the chart’s type to spline and save again. Let the magic happens.

I can also generate the graph series data using a function. For now, I use a for-loop to generate random dummy data, but in a real app, the data could come from an API, web service, or after calculations.
Replace the existing data objects of both the series with the data object:

data: (function() {
  var data = [];

  for (let i = 0; i & lt; = 5; i += 1) {
    data.push({
      x: i,
      y: Math.floor(Math.random() * 10) + 0
    });
  }
  return data;
}())

This
function generates an array of five random integer elements between 0 and 10. The < code > ionViewDidLoad < /code> should now look like this:

data: (function() {
  var data = [];

  for (let i = 0; i & lt; = 5; i += 1) {
    data.push({
      x: i,
      y: Math.floor(Math.random() * 10) + 0
    });
  }
  return data;
}())
ionViewDidLoad() {
  var myChart = HighCharts.chart('container', {
    chart: {
      type: 'spline'
    },
    title: {
      text: 'Fruit Consumption'
    },
    xAxis: {
      categories: ['Apples', 'Bananas', 'Oranges']
    },
    yAxis: {
      title: {
        text: 'Fruit eaten'
      }
    },
    series: [{
      name: 'Jane',
      data: (function() {
        var data = [];
        for (let i = 0; i & lt; = 5; i += 1) {
          data.push({
            x: i,
            y: Math.floor(Math.random() * 10) + 0
          });
        }
        return data;
      }())
    }, {
      name: 'John',
      data: (function() {
        var data = [];
        for (let i = 0; i & lt; = 5; i += 1) {
          data.push({
            x: i,
            y: Math.floor(Math.random() * 10) + 0
          });
        }
        return data;
      }())
    }]
  });
}

 

Save the file and let the app reload in the browser. You will get random graphs like the ones shown below:

Feel free to play with the code and try out new properties and functions. Check out the Official Highcharts Docs to learn more about Highcharts.
I enjoyed this project, and I hope it will help you to set up great charts. I would love to hear your comments and experiences.