How to add HighChart in Angular

The HighChart and D3 are the Javascript library for data visualization. We have a lot of other libraries option to add a chart in Angular. Where D3 is the most popular open source and Highcharts is a product that was created by the Norway-based company, Highsoft.

Highcharts is an SVG-based, multi-platform charting library that has been actively developed since 2009. It makes it easy to add interactive, mobile-optimized charts to your web and mobile projects. It features robust documentation, advanced responsiveness and industry-leading accessibility support.

In this example, we will allow the user to add a random point on the chart through a button on the browser, clicking on the button will invoke add () method to generate a random number on the chart.

Step 1: Setup the project

ng new highChart
cd highChart

npm i --save angular-highcharts highcharts
npm i --save-dev @types/highcharts

Step 2: Create a component SimplechartComponent 

ng generate component simplechart

Add the following code in SimplechartComponent.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'angular-highcharts';

@Component({
  selector: 'app-simplechart',
  templateUrl: './simplechart.component.html',
  styleUrls: ['./simplechart.component.css']
})
export class SimplechartComponent implements OnInit {

  chart = new Chart({
    chart: {
      type: 'line'
    },
    title: {
      text: 'Linechart'
    },
    credits: {
      enabled: false
    },
    series: [{
      name: 'Line 1',
      data: [10, 20, 30, 50, 15, 30, 60,80]
    }]
  });

  constructor() { }

  ngOnInit() {
  }

  add() {
    this.chart.addPoint(Math.floor(Math.random() * 10));
  }
}

ྭWe have to import Chart from Angular-highcharts module in simplechartComponent.ts file and add the following code in simplechartComponent.html file

<button (click)="add()">Add Point!</button>
<div [chart]="chart"></div>

 

Step 3:  Use app-simplechart selector in app.component.html file

<div style="text-align:center">
  <h1>Welcome to {{title}}!</h1>
  <app-simplechart></app-simplechart>
</div>
<h2>Here Simple example of HighChart in Angular </h2>

Atlast we have to register or import the highChar module in app.module.ts file.


import { AppComponent } from './app.component';
import { ChartModule } from 'angular-highcharts';
import { SimplechartComponent } from './components/simplechart/simplechart.component';

@NgModule({
  declarations: [
    AppComponent,
    SimplechartComponent
  ],
  imports: [
    BrowserModule,
    ChartModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }