Angular – Google Charts

Overview

How to use Google Charts with Angular. The code from the GitHub repo has several examples from the Tutorialspoint website. Tutorials Point has detailed documentation on Google Charts for Angular and I highly recommend you bookmark it as your main reference for this library. Also included, is an example of a pie chart using data from an API call to the CDC.

You can get the code here: https://github.com/fullstacksoup/blog-ng-google-charts.

Prerequisites

Install the angular-google-charts library.

npm i angular-google-charts

Import the library in app.module.ts

import { GoogleChartsModule } from 'angular-google-charts';

@NgModule({
  ...
  imports: [
    ...
    GoogleChartsModule,
    ...
  ],
  ...
})
export class AppModule {}

For quick example, run ng generate component bar-chart.

Building the Component

Add the following in a bar-chart.component.ts file add the following:

  title: string;
  type: string;
  data: (string | number)[][];
  columnNames: string[];
  public options: { title: string; colors: string[]; is3D: boolean; };
  width: number;
  height: number;

  ngOnInit(): void {
    this.title = 'Population (in millions)';
    this.type = 'BarChart';
    this.data = [
       ['2012', 900],
       ['2013', 1000],
       ['2014', 1170],
       ['2015', 1250],
       ['2016', 1530]
    ];
    this.columnNames = ['Year', 'Asia'];
    this.options = {
      title: 'Daily Activities',
      is3D: true,
      colors: ['#33440e'],

    };
    this.width = 550;
    this.height = 400;
  }

Add the following to the bar-chart.component.html file:

<google-chart [data]="chartData"
              [title]="title"
              [width]="width"
              [height]="height"
              [type]="type">
</google-chart>

This is a list of the charts that are available:

  • BarChart
  • CandlestickChart
  • Gauge
  • GeoChart
  • OrgChart
  • PieChart
  • Sankey

If you are using an API, the data has to be formatted like the following:

public chartData: any[] = [];
public dataUSTotalArr: any[] = [];
this.dataUSTotalArr = this.dataArr.filter(col => col.state === 'United States' && col.age_group_new === ageGroup && col.sex === gender);

this.dataUSTotalArr.forEach(element => {
  if(element.sex !== 'Unknown') {
    this.chartData.push(['Pneumonia', Number(element.pneumonia_deaths)]);
    this.chartData.push(['Influenza', Number(element.influenza_deaths)]);
    this.chartData.push(['Covid 19', Number(element.covid_19_deaths)]);
  }
});

The full example of an API call to the CDC is available in the pie-chart component from the github repository https://github.com/fullstacksoup/blog-ng-google-charts.

Documentation for Angular Google Charts: https://www.tutorialspoint.com/angular_googlecharts/index.htm.