Angular2 Tutorial: Creating Awesome Animated Charts with Highcharts

Highcharts with Angular2
Highcharts with Angular2

Today I’m going to show you how you can add some really amazing animated charts to your Angular 2 application. We’re going to use a very rich library called Highcharts, it provides a huge variety of charts that you can use on your app. Seriously, they probably have any type of chart you can think about! The only drawback of using highcharts is that it’s not written in Angular 2, so there will be some limitations which I’ll explain later. Since we’re not going to rewrite the charts, this post will be more about how to integrate highchars into your Angular 2 project.

Before we start you obviously need a blank project, if you’re new to angular please follow the instructions on this quickistart to create your project. Having done that you have to add jQuery to the project in order to make highcharts work properly, click here for more details about jQuery and Angular 2 integration.

Now that you have the project let’s add the following scripts to the index.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>

If you followed the instructions from the quickstart your project should have a component called app.component.js, just open it and replace the existing code with the following one:

import {Component} from 'angular2/core';
 
declare var jQuery:any;
 
@Component({
    selector: 'my-chart',
    template: `<div style="width:60%" id="container"></div>`
})
export class AppComponent { 
	private data = [
			{
	            name: 'USA',
	            data: [null, null, null, null, null, 6, 11, 32, 110, 235, 369, 640,
	                1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468, 20434, 24126,
	                27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662,
	                26956, 27912, 28999, 28965, 27826, 25579, 25722, 24826, 24605,
	                24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344, 23586,
	                22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950,
	                10871, 10824, 10577, 10527, 10475, 10421, 10358, 10295, 10104]
	        }, 
            {
            	name: 'USSR/Russia',
	            data: [null, null, null, null, null, null, null, null, null, null,
	                5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471, 3322,
	                4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478,
	                15915, 17385, 19055, 21205, 23044, 25393, 27935, 30062, 32049,
	                33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000,
	                35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000,
	                21000, 20000, 19000, 18000, 18000, 17000, 16000]
	        }];
 
    ngAfterViewInit() {
    	this.renderChart();
    }
 
    renderChart(){
    	jQuery('#container').highcharts({
	        chart: {
	            type: 'area'
	        },
	        title: {
	            text: 'US and USSR nuclear stockpiles'
	        },
	        subtitle: {
	            text: 'Source: thebulletin.metapress.com'
	        },
	        xAxis: {
	            allowDecimals: false,
	            labels: {
	                formatter: function () {
	                    return this.value;
	                }
	            }
	        },
	        yAxis: {
	            title: {
	                text: 'Nuclear weapon states'
	            },
	            labels: {
	                formatter: function () {
	                    return this.value / 1000 + 'k';
	                }
	            }
	        },
	        tooltip: {
	            pointFormat: '{series.name} produced <b>{point.y:,.0f}</b>' +
	            			 '<br/>warheads in {point.x}'
	        },
	        plotOptions: {
	            area: {
	                pointStart: 1940,
	                marker: {
	                    enabled: false,
	                    symbol: 'circle',
	                    radius: 2,
	                    states: {
	                        hover: {
	                            enabled: true
	                        }
	                    }
	                }
	            }
	        },
	        series: this.data
	    });
    }
}

Now let me explain what is happening on this code, the most important thing is the method renderChart() called by the hook ngAfterViewInit(), as the name suggests it contains the code responsible for rendering the component, it’s where I’m providing all the parameters like title, labels, size and colors so highcharts can create the chart for me (you can check all the available options at the Highcharts API Reference). Lastly, jQuery will replace the only div in the template with the chart returned by highcharts.

Note that once renderChart() is called Angular 2 has no control over the component anymore, highcharts and jQuery are doing the entire job, which means Angular 2 won’t know how to deal with the chart once it’s created, and it won’t be able to automatically refresh it if something changes, as far as angular knows there’s just a div on the screen, so every time the data is modified you’ll have to call renderChart() again to be able to refresh the chart, that’s the limitation I was talking about.

That being said, you can now run your project and start customizing your chart! Please leave a comment if you need any help.

Recommended for you

Passing Parameters to an Angular2 Component One of the greatest advantages of using components is reusability, which means once you've create your component you can use it in several places across your project without having to recreate it everytime. But for that to be possible we have to be able to pass parameters to our components, that's w...
Angular2 Tutorial: Creating Attribute Directives According to Angular2 documentation, directives are classes that can change the component behavior or/and appearance, which basically means they can add CSS classes and styles, register events and manipulate the component's properties. In this tutorial I'm going to show you how to create a very ...
Angular2: How to Pass Callback Functions to a Component There are lots of situations where it's useful to pass a function to an angular2 component, for instance, when our component is a dialog and we have to perform an specific task when it closes, or pass the action of one of its buttons, or even events like keypress, resize, mouseover, etc. If you're r...
Tutorial: Creating an Angular2 Autocomplete Angular 2 Autocomplete Before we begin I just want to say that I'm not going to use any third-party component for this tutorial, I'm going to create an autocomplete from scratch, my goal is to just make it show the suggestions and allow the user to select one, but if you need more advanced featu...

5 comments on “Angular2 Tutorial: Creating Awesome Animated Charts with Highcharts

  1. Chris Walker

    Thanks for a useful how-to. There seem to be two errors in the instructions. Could be these work OK in your environment, but they cause errors when you set up the quickstart from scratch.

    import {Component} from 'angular2/core';

    This causes a 404 error. I had to change it to the original import in the quickstart:

    import {Component} from 'angular/core';

    The selector for the chart version of AppComponent is “my-chart”, but the tag in index.html is “my-app”. One of these needs to be changed so they both match.

  2. Bilal

    i followed the angular quickstart steps. and then followed yours i could not get the charts instead i got the output of hello angular. What am i missing

  3. faisal

    hi leo,

    Please if you can help.
    After the angular 4 http service call , renderChart numeric array data is not being initialized that says undefined.
    that gives impression to me. graph data cannot be initialized with http service and ajax returned data .

    Please if you can help?

    thanks!
    Faz

Leave a Reply to faisal Cancel reply

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

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>