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

Angular2 Error: Cannot assign to a reference or variable! ; Zone: ; Task: Promise.then ... This error occurs when you try to define a template reference variable with the same name of an existing variable, like for example in this case: @Component({ selector: 'example', template: ` Name ` }) export class AppComponent { name; } As you can see, the...
Angular2 Tutorial: Developing a Realtime Chat App Angular 2 Chat Application Hi guys, today we're going to make an awesome chat application with Angular2, NodeJS and Socket.io, this tutorial will involve quite a lot of things, and there are also lots of small details, so it will be a little bit longer than usual. To easily understand and make t...
Creating an Angular2 Datatable from Scratch PART 2: Filtering the Data Continuing from where we stopped at Part 1, today we're going to add the filter functionality to the table, but before we start let's do some styling. I'm going to use Bootstrap, but if you don't want you don't have to, feel free to style your component as you like. But if you decide to use Bootstra...
Angular 2 Tutorial: Adding HotKeys (Keyboard shortcuts) to a Component Arguably hotkeys can substantially increase the usability of an application, the less the users have to touch the mouse the better will be their experience with the application. Luckily for us there is a very easy way of defining hotkeys on angular2, which is by adding a listener to the host comp...

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

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>