{"id":17905,"date":"2019-04-08T08:46:03","date_gmt":"2019-04-08T06:46:03","guid":{"rendered":"http:\/\/www.highcharts.com\/blog\/?p=17905"},"modified":"2026-01-12T11:22:35","modified_gmt":"2026-01-12T11:22:35","slug":"highcharts-and-angular-7","status":"publish","type":"post","link":"https:\/\/www.highcharts.com\/blog\/integration\/highcharts-and-angular-7\/","title":{"rendered":"Highcharts and Angular 7"},"content":{"rendered":"<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>In this tutorial, I will show you how to use Angular 7 and Highcharts to create a simple web page that fetches data via an API and generates charts from it.<\/p>\n<p>More specifically, we want our web page to render an interactive scatter chart displaying dates (timestamps) in chronological order along the x-axes and values for each timestamp along the y-axes. The entire project is saved in this <a href=\"https:\/\/github.com\/m-haziq\/highcharts-simplified\/\">GitHub link<\/a> and here is the link to the <a href=\"https:\/\/api.myjson.com\/bins\/13lnf4\">dummy data<\/a>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-17907\" src=\"https:\/\/wp-assets.highcharts.com\/www-highcharts-com\/blog\/wp-content\/uploads\/2019\/04\/05095601\/highcharts-simplified-nonhead2.gif\" alt=\"\" width=\"1160\" height=\"432\" \/><\/p>\n<p>I divided the tutorial into two main sections; the first section is about how to set up the project and the second one is about how to integrate Highcharts.<\/p>\n<p>Let\u2019s get started \ud83d\ude42<\/p>\n<h4>Setup the project<\/h4>\n<p>The first thing to do is to install Angular CLI using this command line <code>npm install -g @angular\/cli<\/code>. To be sure that the Angular CLI is well installed, I verify that I read the version, for example, <code>ng --version<\/code><\/p>\n<p>If there is no error, I am happy \ud83d\ude42<\/p>\n<p>Then create a folder for the project, enter it, and run the following command: <code>ng new angular7-highcharts<\/code>. Once done, go to the angular7-highcharts folder, then you can run the project using these <code>ng serve<\/code>.The application is running on <code>http:\/\/localhost:4200\/<\/code><\/p>\n<p>For better organization, I created a component dedicated to the chart view using this command line ng generate component <code>output-graph<\/code>.<\/p>\n<p>The new component, <code>output-graph<\/code>, is found under <code>\/src\/app\/<\/code> and consists of four different files:<\/p>\n<ul>\n<li><code>.CSS<\/code>: All CSS for styles should go into this file.<\/li>\n<li><code>.HTML<\/code>: This file includes HTML template and all HTML tags.<\/li>\n<li><code>.TS<\/code>: This file includes all typescript code, the business logic, API calls, and data manipulation.<\/li>\n<li><code>.SPEC.TS<\/code>:All unit tests go into this file.<\/li>\n<\/ul>\n<p><i><b>Remark: <\/b>I will not cover the Angular 7 unit tests, for those who don\u2019t know it, since it is a topic that requires a tutorial of its own.<\/i><\/p>\n<p>The last step in this section is to modify the \u201capp component\u201d according to the project\u2019s need, by removing the extra default content from app\/app.component.html and including my new component as:<\/p>\n<pre>&lt;div id=\"main-head\" style=\"text-align:center\"&gt;\r\n  &lt;h1&gt;\r\n    Welcome to {{ title }}!\r\n  &lt;\/h1&gt;\r\n  &lt;app-output-graph&gt;&lt;\/app-output-graph&gt;\r\n&lt;\/div&gt;\r\n&lt;router-outlet&gt;&lt;\/router-outlet&gt;\r\n<\/pre>\n<p><code>app-output-graph<\/code> is the selector of the new component. Now, I can add\/modify the content of the parent component by changing variables i.e. title in the file <code>app\/app.component.ts<\/code> as:<\/p>\n<pre>...\r\nexport class AppComponent {\r\n  title = 'High Charts Simplified';\r\n}<\/pre>\n<p>And finally, I style the parent component <code>app\/app.component.css<\/code> file as:<\/p>\n<pre>#main-head{\r\n  background-color: cornflowerblue;\r\n  text-align: center;\r\n}<\/pre>\n<h4>Integrate Highcharts<\/h4>\n<p>Next, we want to focus on charting, using Highcharts. This step is simple and straightforward.<\/p>\n<p>First, install the library using via the command line <code>npm install highcharts<\/code>.<\/p>\n<p>Then, import the Highcharts library into the <code>output-graph<\/code>.component.ts, because, as mentioned above, all logic resides in the <code>.ts<\/code> files.<\/p>\n<pre>import { Component, OnInit } from '@angular\/core';\r\nimport * as Highcharts from 'highcharts';\r\n\r\ndeclare var require: any;\r\nlet Boost = require('highcharts\/modules\/boost');\r\nlet noData = require('highcharts\/modules\/no-data-to-display');\r\nlet More = require('highcharts\/highcharts-more');\r\n\r\nBoost(Highcharts);\r\nnoData(Highcharts);\r\nMore(Highcharts);\r\nnoData(Highcharts);\r\n\r\n@Component({\r\n  selector: 'app-output-graph',\r\n  templateUrl: '.\/output-graph.component.html',\r\n  styleUrls: ['.\/output-graph.component.css']\r\n})\r\nexport class OutputGraphComponent implements OnInit {\r\n  public options: any = {\r\n    chart: {\r\n      type: 'scatter',\r\n      height: 700\r\n    },\r\n    title: {\r\n      text: 'Sample Scatter Plot'\r\n    },\r\n    credits: {\r\n      enabled: false\r\n    },\r\n    tooltip: {\r\n      formatter: function() {\r\n        return '<b>x: <\/b>' + Highcharts.dateFormat('%e %b %y %H:%M:%S', this.x) +\r\n          ' \r\n <b>y: <\/b>' + this.y.toFixed(2);\r\n      }\r\n    },\r\n    xAxis: {\r\n      type: 'datetime',\r\n      labels: {\r\n        formatter: function() {\r\n          return Highcharts.dateFormat('%e %b %y', this.value);\r\n        }\r\n      }\r\n    },\r\n    series: [\r\n      {\r\n        name: 'Normal',\r\n        turboThreshold: 500000,\r\n        data: [[new Date('2018-01-25 18:38:31').getTime(), 2]]\r\n      },\r\n      {\r\n        name: 'Abnormal',\r\n        turboThreshold: 500000,\r\n        data: [[new Date('2018-02-05 18:38:31').getTime(), 7]]\r\n      }\r\n    ]\r\n  }\r\n  constructor() { }\r\n\r\n  ngOnInit(){\r\n    Highcharts.chart('container', this.options);\r\n  }\r\n}<\/pre>\n<p>We are all set and may run the application with the command <code>ng serve<\/code>.<br \/>\nWhoaa! The application is displaying an interactive chart with two hard-coded points on it.<\/p>\n<p>Before going any further, let\u2019s take a look at how the Highcharts library works. For more details check the <a href=\"https:\/\/api.highcharts.com\/highcharts\/\">official API documentation<\/a>.<\/p>\n<ul>\n<li><b>chart<\/b> includes the chart type.<\/li>\n<li><b>Title<\/b> includes chart title.<\/li>\n<li><b>Tooltip<\/b> has the tooltip\u2019s customizations.<\/li>\n<li><b>Series includes<\/b> the data and categories of data. In this project, I am using normal and abnormal data generated from an AI (artificial intelligence data).<\/li>\n<\/ul>\n<p>I am also using the method <code>ngOnInit()<\/code> that is a trigger to call the application to draw the chart inside a div element. The div element has an id equals to <code>container<\/code> with default settings as <code>this.options<\/code>.<\/p>\n<pre>\u2026\r\nngOnInit(){\r\n    Highcharts.chart('container', this.options);\r\n  }\r\n}<\/pre>\n<p>Now, let\u2019s try to pull some data from an external source, using this <a href=\"https:\/\/api.myjson.com\/bins\/13lnf4\">API<\/a>.<\/p>\n<p>Let\u2019s return to the .ts file again <code>output-graph\/output-graph.component.ts<\/code>, then make the right modification to fetch the data from the API:<\/p>\n<pre>import { Component, OnInit } from '@angular\/core';\r\nimport * as Highcharts from 'highcharts';\r\nimport { HttpClient } from '@angular\/common\/http';\r\nimport { interval, Subscription } from 'rxjs';\r\n\r\ndeclare var require: any;\r\nlet Boost = require('highcharts\/modules\/boost');\r\nlet noData = require('highcharts\/modules\/no-data-to-display');\r\nlet More = require('highcharts\/highcharts-more');\r\n\r\nBoost(Highcharts);\r\nnoData(Highcharts);\r\nMore(Highcharts);\r\nnoData(Highcharts);\r\n\r\n@Component({\r\n  selector: 'app-output-graph',\r\n  templateUrl: '.\/output-graph.component.html',\r\n  styleUrls: ['.\/output-graph.component.css']\r\n})\r\nexport class OutputGraphComponent implements OnInit {\r\n  public options: any = {\r\n    chart: {\r\n      type: 'scatter',\r\n      height: 700\r\n    },\r\n    title: {\r\n      text: 'Sample Scatter Plot'\r\n    },\r\n    credits: {\r\n      enabled: false\r\n    },\r\n    tooltip: {\r\n      formatter: function() {\r\n        return '<b>x: <\/b>' + Highcharts.dateFormat('%e %b %y %H:%M:%S', this.x) +\r\n          ' \r\n <b>y: <\/b>' + this.y.toFixed(2);\r\n      }\r\n    },\r\n    xAxis: {\r\n      type: 'datetime',\r\n      labels: {\r\n        formatter: function() {\r\n          return Highcharts.dateFormat('%e %b %y', this.value);\r\n        }\r\n      }\r\n    },\r\n    series: [\r\n      {\r\n        name: 'Normal',\r\n        turboThreshold: 500000,\r\n        data: []\r\n      },\r\n      {\r\n        name: 'Abnormal',\r\n        turboThreshold: 500000,\r\n        data: []\r\n      }\r\n    ]\r\n  }\r\n  subscription: Subscription;\r\n  constructor(private http: HttpClient) { }\r\n\r\n  ngOnInit(){\r\n    \/\/ Set 10 seconds interval to update data again and again\r\n    const source = interval(10000);\r\n\r\n    \/\/ Sample API\r\n    const apiLink = 'https:\/\/api.myjson.com\/bins\/13lnf4';\r\n\r\n    this.subscription = source.subscribe(val =&gt; this.getApiResponse(apiLink).then(\r\n      data =&gt; {\r\n        const updated_normal_data = [];\r\n        const updated_abnormal_data = [];\r\n        data.forEach(row =&gt; {\r\n          const temp_row = [\r\n            new Date(row.timestamp).getTime(),\r\n            row.value\r\n          ];\r\n          row.Normal === 1 ? updated_normal_data.push(temp_row) : updated_abnormal_data.push(temp_row);\r\n        });\r\n        this.options.series[0]['data'] = updated_normal_data;\r\n        this.options.series[1]['data'] = updated_abnormal_data;\r\n        Highcharts.chart('container', this.options);\r\n      },\r\n      error =&gt; {\r\n        console.log('Something went wrong.');\r\n      })\r\n    );\r\n  }\r\n\r\n  getApiResponse(url) {\r\n    return this.http.get(url, {})\r\n      .toPromise().then(res =&gt; {\r\n        return res;\r\n      });\r\n  }\r\n}<\/pre>\n<p>To make this project more dynamic, let\u2019s add this function <code>getApiResponse(url)<\/code> to call the API each 10 seconds to get fresh data. I also import <code>HttpClientModule<\/code> to initiate HTTP request and responses in angular apps:<\/p>\n<pre>...\r\nimport { HttpClientModule } from '@angular\/common\/http';\r\n...\r\n@NgModule({\r\n  ...\r\n  imports: [\r\n    BrowserModule,\r\n    AppRoutingModule,\r\n    HttpClientModule\r\n  ],\r\n  ...\r\n})<\/pre>\n<p>Ok, our application is complete now. Let\u2019s run it again using this command line <code>ng serve<\/code>.<\/p>\n<p>Congrats! If you have followed along, you\u2019ve now created an Angular application with dynamic data bindings! I hope this project will help you to understand better how to build an Angular application and how to integrate the Highcharts library. Feel free to add your comment or question below; I will be happy to answer.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A nice tutorial to get started with Highcharts using Angular 7.<\/p>\n","protected":false},"author":239,"featured_media":21614,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"meta_title":"","meta_description":"","hc_selected_options":[],"footnotes":""},"categories":[1105],"tags":[822,1094,1031],"coauthors":[770],"class_list":["post-17905","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-integration","tag-angular","tag-highcharts-core","tag-javascript"],"_links":{"self":[{"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/posts\/17905","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/users\/239"}],"replies":[{"embeddable":true,"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/comments?post=17905"}],"version-history":[{"count":1,"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/posts\/17905\/revisions"}],"predecessor-version":[{"id":29193,"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/posts\/17905\/revisions\/29193"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/media\/21614"}],"wp:attachment":[{"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/media?parent=17905"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/categories?post=17905"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/tags?post=17905"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.highcharts.com\/blog\/wp-json\/wp\/v2\/coauthors?post=17905"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}