HighCharts In Angular 7

Introduction

Here, we will learn about how we can create a chart in Angular 7. There are lots of chart libraries available for Angular 7. We will going to use Highchart and will bind data from web API to make dynamic data binding.

Prerequisite:

  • Basic knowledge of Angular 7
  • Visual Studio Code
  • Angular CLI must be installed
  • Node JS must be installed

Let’s get started

Open the Visual Studio code and open a new Terminal.

Type the following command in it.

ng new angular7-highcharts

Yes for Angular routing and use CSS for the stylesheet.

We will also install the Highchart as we are going to use this library.

Open the project in Visual Studio Code by opening the folder.

Choose our project folder and open it.

Now, let’s create the component for the project, so open the terminal and type the following command.

ng g c highchart-demo

Done with installation and project setup. Now we will add logic for highchart.

Open app.component.html file and add the highlighted line in it.

<app-highchart-demo></app-highchart-demo>

Open the highchart-demo.component.ts file replace the below code in it.

import { Component, OnInit } from '@angular/core';
import * as Highcharts from 'highcharts';
import { HttpClient } from '@angular/common/http';
import { interval, Subscription } from 'rxjs';

declare var require: any;
let Boost = require('highcharts/modules/boost');
let noData = require('highcharts/modules/no-data-to-display');
let More = require('highcharts/highcharts-more');

Boost(Highcharts);
noData(Highcharts);
More(Highcharts);
noData(Highcharts);

@Component({
  selector: 'app-highchart-demo',
  templateUrl: './highchart-demo.component.html',
  styleUrls: ['./highchart-demo.component.css']
})
export class HighchartDemoComponent implements OnInit {
  public options: any = {
    chart: {
      type: 'line',
      height: 500
    },
    title: {
      text: 'Sample Scatter Plot'
    },
    credits: {
      enabled: false
    },
    tooltip: {
      formatter: function() {
        return 'x: ' +  this.x +   '  y: ' + this.y;
      }
    },
    xAxis: {
      categories: []
    },
    series: [
      {
        name: 'Mr. Faisal',
        data: []
      },
      {
        name: 'Mr. Pathan',
        data: []
      }
    ]
  }
  subscription: Subscription;
  constructor(private http: HttpClient) { }

  ngOnInit(){
    // update data again and again after every 5 seconds interval
    //const source = interval(5000);

    // My dummy API
    const apiLink = 'https://api.myjson.com/bins/zg8of';

    this.getApiResponse(apiLink).then(
    //this.subscription = source.subscribe(val =>this.getApiResponse(apiLink).then(
      data => {
        const faisalArr = [];
        const pathanArr = [];
        const xAxisArr = [];

        data.forEach(row => {
          const temp_row = [
            row.Sales_Figure
          ];
          if(xAxisArr.find(ob => ob === row.Month) === undefined){
             xAxisArr.push(row.Month)
          }
          row.Name === 'Faisal' ? faisalArr.push(temp_row) : pathanArr.push(temp_row);
        });

        this.options.xAxis['categories'] = xAxisArr;
        this.options.series[0]['data'] = faisalArr;
        this.options.series[1]['data'] = pathanArr;
        Highcharts.chart('container', this.options);
      },
      error => {
        console.log('Something went wrong.');
      })
    //)
    ;
  }

  async getApiResponse(url: string) {
    const res = await this.http.get<any[]>(url, {})
      .toPromise();
    return res;
  }
}

Open the app.module.ts file present at the root folder and add the HttpClientModule references there.

import { HttpClientModule } from '@angular/common/http';

Open the highchart-demo.component.html file add the below HTML tag in it to display our chart.

<div id="container"></div>

That’s it, fire below command to see the magic!

ng serve

open your browser on http://localhost:4200/ or click on “http://localhost:4200/” it.

Output:

Please give your valuable feedback/comments/questions about this article below. Please let me know how you like and understand this article and how I could improve it.

You can download the source code from here

6 Comments

  1. Hasan

    AfterViewInit should be used instead of OnInit. The only thing I could cope with was this lifecycle hook.

    0
    0
    Reply
  2. Fahad

    sir please give access to your Api, I don’t know the form of data in Api

    0
    0
    Reply
    1. Faisal Pathan

      You can use any free API like https://any-api.com/ my API has limited time access so we can’t access that API anymore.

      0
      0
      Reply
  3. Unknow

    It’s not supporting Angular 9..No error with no data.

    0
    0
    Reply
  4. Gilberto

    I get the “No data to display ” error, even when i copy and paste your code

    0
    0
    Reply
    1. Faisal Pathan

      Do one thing, download source code and run. and check is run in your machine or not.

      0
      0
      Reply

Submit a Comment

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

Subscribe

Select Categories