How to use Google Chart in Angular 4+

Google Charts are based on HTML5/SVG technology. So not required any extra plugin. All charts are interactive and many are zoomable. Using Google charts you can create Geo Chart, Scatter Chart, Column Chart, Histogram, Bar Chart, Combo Chart, Line Chart, Pie Chart, Donut Chart and so on. In this article, we discuss how to create a “pie chart” in Angular.

First, we need to add the main javascript in index.html file display in below

 < script src="https://www.gstatic.com/charts/loader.js"></script>
 < script type="text/javascript">
    // Load the Visualization API and the corechart package.
    google.charts.load('current', {'packages':['corechart']});
 </script>



Second, We need to create a Google chart component who handle the drawing of the chart from other components. Display in below code.

import {Directive,ElementRef,Input,OnInit} from '@angular/core';
declare var google:any;
declare var googleLoaded:any;
@Directive({
  selector: '[GoogleChart]'
})
export class GoogleChartComponent implements OnInit {
  public _element:any;
  @Input('chartType') public chartType:string;
  @Input('chartOptions') public chartOptions: Object;
  @Input('chartData') public chartData: Object;
  constructor(public element: ElementRef) {
    this._element = this.element.nativeElement;
  }
  ngOnInit() {
    setTimeout(() =>{
      google.charts.load('current', {'packages':['corechart']});
        setTimeout(() =>{
          this.drawGraph(this.chartOptions,this.chartType,this.chartData,this._element)
        },1000);
      },1000
    );
  }
  drawGraph (chartOptions,chartType,chartData,ele) {
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
      var wrapper;
      wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable:chartData ,
        options:chartOptions || {},
        containerId: ele.id
      });
      wrapper.draw();
    }
  }
}

Third, we need to import our component into “app.module.ts” file.

import { GoogleChartComponent } from './google-chart/google-chart.component';
...................
@NgModule({
  .........
  declarations: [
                GoogleChartComponent,
            ...
           ]
})
export class AppModule(){}



Now you can use this component in any other components display in below code


//here 
ChartData - Its array of the data which you want to display
chartType - Which type of chat you want to use.
chartOptions - You can set title, height, width so on

<div id="chart"  style="height:400px" [chartData]="ChartData" [chartOptions] = "ChartOptions" chartType="GeoChart" GoogleChart></div>
Spread the love
  • 77
  •  
  •  
  •  
  • 1
  •  
  •  
  •