SHARE:

Using Google Charts in Angular 4 project, part 2

Integrate Google Charts and make reusable chart components

We previously saw how to use Google Charts in an classical HTML5 / Javascript page, now it’s time to see how we can make it work in an Angular 4 project. We will still use use the chart as sample (Google Pie Chart)

Let’s get started !

Step 1 :

Add the javascript library file in index.html :

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

Step 2 :

To make Google Charts more reusable as possible, let’s make a class named GoogleChartsBaseService that does the redundant job : loading the library and manage the callback that we described in the previous article:

declare var google: any;

export class GoogleChartsBaseService {
  constructor() { 
    google.charts.load('current', {'packages':['corechart']});
  }

  protected buildChart(data: any[], chartFunc: any, options: any) : void {
    var func = (chartFunc, options) => {
      var datatable = google.visualization.arrayToDataTable(data);
      chartFunc().draw(datatable, options);
    };   
    var callback = () => func(chartFunc, options);
    google.charts.setOnLoadCallback(callback);
  }
  
}

As you can I added this instruction at the top : declare var google: any;

This is because with TypeScript, and Typescript doesn’t know the definition of google variable, so we declared it, corresponding to the global variable declared in Google Charts library. Typescript will be able to transpile it.

buildChart encapsulate the callback definition, the data mapping (Array to Datatable), and the setOnLoadCallback method call.

Step 3 :

Let’s make a PieChartConfig model to bind it’s configuration :

export class PieChartConfig {
    title: string;
    pieHole: number

    constructor(title: string, pieHole: number) {
        this.title = title;
        this.pieHole = pieHole;
    }
}

title member is the chart title

pieHole is corresponding to the ratio of radii between the hole and the chart (value from 0 to 1)

Step 4 :

Let’s build GooglePieChartService , this service will extends GoogleChartsBaseService 

Because we use Typescript as you know, let’s add at the top : declare var google: any;

We need to encapsulate object google.visualization in a callback (arrow function works too) because this object is not set yet by the framework (during execution of setOnLoadCallback)

Here we are :

import { GoogleChartsBaseService } from './google-charts.base.service';
import { Injectable } from '@angular/core';
import { PieChartConfig } from './../Models/PieChartConfig';

declare var google: any;

@Injectable()
export class GooglePieChartService extends GoogleChartsBaseService {

  constructor() { super(); }

  public BuildPieChart(elementId: String, data: any[], config: PieChartConfig) : void {  
    var chartFunc = () => { return new google.visualization.PieChart(document.getElementById(elementId)); };
    var options = {
            title: config.title,
            pieHole: config.pieHole,
      };

    this.buildChart(data, chartFunc, options);
  }
}

Because it’s an injectable service (singleton), don’t forget to add it in providers array in app.module.ts

We built a base service and PieChartService, that means the logic is set in services and it provides more flexibilty in your app, we decoupled as much as possible Google Charts with our app

Step 5 :

It’s time to make reusable components

we need 3 parameters in input

1- Html id attribute of the div we want to fill with the chart

2- The chart configurations options

3- Data

Here we are:

import { Component, Input, OnInit } from '@angular/core';

import { GooglePieChartService } from './../../Services/google-pie-chart.service';
import { PieChartConfig } from './../../Models/PieChartConfig';

declare var google: any;


@Component({
  selector: 'pie-chart',
  templateUrl: './piechart.component.html'
})
export class PieChartComponent implements OnInit {

    @Input() data: any[];
    @Input() config: PieChartConfig;
    @Input() elementId: String;

    constructor(private _pieChartService: GooglePieChartService) {}

    ngOnInit(): void {
        this._pieChartService.BuildPieChart(this.elementId, this.data, this.config); 
    }
}

the pie chart conponent html file :

<div id="{{elementId}}" style="width: 800px; height: 400px;"></div>

We definitely have to declare them into app.module.ts as well

Step 6 :

Let’s add data, config and try !

We will build a component (named DashboardComponent) that display our reusable ours Pie charts and provide them data.

Ts file :

import { ComboChartConfig } from './../Models/ComboChartConfig';
import { Component } from '@angular/core';
import { PieChartConfig } from './../Models/PieChartConfig';

@Component({
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent {
  title = 'Reusable charts sample';

  data1: any[];
  config1: PieChartConfig;
  elementId1: String;

  data2: any[];
  config2: PieChartConfig;
  elementId2: String;
  
  ngOnInit(): void {     

    //Piechart1 Data & Config
    this.data1 = [['Task', 'Hours per Day'],
    ['Eat',      3],
    ['Commute',  2],
    ['Watch TV', 5],
    ['Video games', 4],
    ['Sleep',    10]];

    this.config1 = new PieChartConfig('My Daily Activities at 20 years old', 0.4);
    this.elementId1 = 'myPieChart1';

    //Piechart2 Data & Config
    this.data2 = [['Task', 'Hours per Day'],
                  ['Work',     11],
                  ['Eat',      2],
                  ['Commute',  2],
                  ['Watch TV', 2],
                  ['Sleep',    7]]

    this.config2 = new PieChartConfig('My Daily Activities at 30 years old', 0.4);
    this.elementId2 = 'myPieChart2';
  }

}

HTML file :

<h2>{{title}}</h2>

<div class="divTable">
    <div class="divTableBody">
        <div class="divTableRow">
            <div class="divTableCell"><pie-chart [data]="data1" [config]="config1" [elementId]="elementId1"></pie-chart></div>
            <div class="divTableCell"><pie-chart [data]="data2" [config]="config2" [elementId]="elementId2"></pie-chart></div>
        </div>
    </div>
</div>

And here is the associated css in dashboard.component.css

Don’t forget to declare that component into app.module.ts

And now …..

Awesome right? 🙂

Now you know how to make reusable Google Charts Angular 4 components! 🙂 🙂 🙂

Here the Url of the project if you want to test in your browser : http://demoangular4.azurewebsites.net/

If you want to get the complete source code you can find it there, you can also contribute! : https://github.com/AnthonyGiretti/Angular4-GoogleCharts

 

 

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.

1,007 thoughts on “Using Google Charts in Angular 4 project, part 2

  1. Pingback: buy cialis uk
  2. Pingback: buy cialis usa
  3. Pingback: buy cialis germany
  4. Pingback: deiun.flazio.com
  5. Pingback: kerbnt.flazio.com
  6. Pingback: canadian viagra
  7. Pingback: canadian drugs
  8. Pingback: hekluy.ucraft.site
  9. Pingback: madridbet
  10. Pingback: meritroyalbet
  11. Pingback: meritroyalbet
  12. Pingback: eurocasino
  13. Pingback: canada drug
  14. Pingback: canadian pharmacy
  15. Pingback: canadadrugs
  16. Pingback: buy viagra 25mg
  17. Pingback: aonubs.website2.me
  18. Pingback: dkyubn.bizwebs.com
  19. Pingback: canadian pharmacys
  20. Pingback: meritroyalbet
  21. Pingback: canadian drugstore
  22. Pingback: eurocasino
  23. Pingback: madridbet
  24. Pingback: bahis siteleri
  25. Pingback: canadian pharmacys
  26. Pingback: canadian drug
  27. Pingback: canadian drug
  28. Pingback: meritroyalbet
  29. Pingback: 1invitations
  30. Pingback: meritking
  31. Pingback: lsdevs.iwopop.com
  32. Pingback: canadian viagra
  33. Pingback: selaw.flazio.com
  34. Pingback: canada viagra
  35. Pingback: canada drug
  36. Pingback: kawerc.proweb.cz
  37. Pingback: pedrew.zombeek.cz
  38. Pingback: canada pharmacy
  39. Pingback: kawers.micro.blog
  40. Pingback: alewrt.flazio.com
  41. Pingback: buy cialis delhi
  42. Pingback: buy generic cialis
  43. Pingback: cialis
  44. Pingback: canada medication
  45. Pingback: buy viagra 25mg
  46. Pingback: buy viagra online
  47. Pingback: bahis siteleri
  48. Pingback: A片
  49. Pingback: porno}
  50. Pingback: buy viagra no rx
  51. Pingback: buy viagra
  52. Pingback: meriking
  53. Pingback: buy viagra uk
  54. Pingback: canadian viagra
  55. Pingback: madridbet
  56. Pingback: stromectol espana
  57. Pingback: canada rx
  58. Pingback: is stromectol safe
  59. Pingback: stromectol biam
  60. Pingback: what is stromectol
  61. Pingback: online pharmacies
  62. Pingback: Northwest Pharmacy
  63. Pingback: canada viagra
  64. Pingback: stromectol france
  65. Pingback: canadian drugstore
  66. Pingback: cialis from canada
  67. Pingback: madridbet
  68. Pingback: logilogilogi
  69. Pingback: zamazingo1
  70. Pingback: logarkomx
  71. Pingback: Bahiscom
  72. Pingback: Betmatik
  73. Pingback: Betist
  74. Pingback: Cratosslot.
  75. Pingback: Betlike
  76. Pingback: Betebet
  77. Pingback: Mariobet
  78. Pingback: Tempobet
  79. Pingback: Tipobet
  80. Pingback: Klasbahis
  81. Pingback: Vdcasino
  82. Pingback: Casinoeuro
  83. Pingback: imajbet
  84. Pingback: imajbet giris
  85. Pingback: Sahabet
  86. Pingback: stromectol price
  87. Pingback: stromectol
  88. Pingback: 1xbet
  89. Pingback: Bahigo
  90. Pingback: Bahis siteleri
  91. Pingback: Onwin
  92. Pingback: Kralbet
  93. Pingback: Tipobet Giriş
  94. Pingback: Betkolik
  95. Pingback: Casino Siteleri
  96. Pingback: Bettilt
  97. Pingback: Betasus
  98. Pingback: Dinamobet
  99. Pingback: Jojobet
  100. Pingback: Jojobet giriş
  101. Pingback: Hepsibahis
  102. Pingback: Marsbahis
  103. Pingback: meritking
  104. Pingback: stromectol reviews
  105. Pingback: canadian drug
  106. Pingback: grandpashabet
  107. Pingback: online pharmacies
  108. Pingback: buy viagra usa
  109. Pingback: viagra canada
  110. Pingback: online pharmacy
  111. Pingback: canadian pharmacys
  112. Pingback: best drugs for ed
  113. Pingback: canadian pharmacy
  114. Pingback: canadadrugs
  115. Pingback: canadian drugs
  116. Pingback: canada pharmacies
  117. Pingback: drugs for sale
  118. Pingback: madridbet
  119. Pingback: fuck google
  120. Pingback: canadian drugs
  121. Pingback: okey oyna
  122. Pingback: canadadrugs
  123. Pingback: viagra canada
  124. Pingback: canada pharmacy
  125. Pingback: canadian rx
  126. Pingback: madridbet
  127. Pingback: pharmacy canada
  128. Pingback: www.dibiz.comgdooc
  129. Pingback: canadian drugstore
  130. Pingback: canadian rx
  131. Pingback: canadian rx
  132. Pingback: canada viagra
  133. Pingback: ギャンブル
  134. Pingback: canada rx
  135. Pingback: buy viagra 25mg
  136. Pingback: сука пари
  137. Pingback: meritking
  138. Pingback: meritking
  139. Pingback: grandpashabet
  140. Pingback: meritking
  141. Pingback: meritking giriş
  142. Pingback: Autoapprove List
  143. Pingback: grandpashabet
  144. Pingback: fuck google
  145. Pingback: porn
  146. Pingback: fuck
  147. Pingback: porn
  148. Pingback: sdasdascascasd
  149. Pingback: customized essays
  150. Pingback: cialis trial pack
  151. Pingback: cialis 5 mg
  152. Pingback: buy 1 viagra pill
  153. Pingback: tadalafil walmart
  154. Pingback: sublingual cialis
  155. Pingback: tadalafil samples
  156. Pingback: best viagra uk
  157. Pingback: bactrim percocet
  158. Pingback: glucophage ahumada
  159. Pingback: metronidazole pack
  160. Pingback: child porn
  161. Pingback: child porn
  162. Pingback: keflex good rx
  163. Pingback: child porn
  164. Pingback: grandpashabet
  165. Pingback: porn
  166. Pingback: grandpashabet
  167. Pingback: grandpashabet
  168. Pingback: porno izle
  169. Pingback: child porn
  170. Pingback: grandpashabet
  171. Pingback: cratosroyalbet
  172. Pingback: child porn
  173. Pingback: diclofenac alcohol
  174. Pingback: celebrex safety
  175. Pingback: child porn
  176. Pingback: child porn
  177. Pingback: raw semaglutide uk
  178. Pingback: acarbose precose
  179. Pingback: actos lyrica
  180. Pingback: child porn
  181. Pingback: porn
  182. Pingback: ivermectin 1%cream
  183. Pingback: child porn
  184. Pingback: child porn
  185. Pingback: child porn
  186. Pingback: us online pharmacy
  187. Pingback: sex historie
  188. Pingback: ivermectin 20 mg
  189. Pingback: vardenafil levitra
  190. Pingback: ivermectin human
  191. Pingback: ananın amı
  192. Pingback: child porn
  193. Pingback: child porn
  194. Pingback: child porn
  195. Pingback: child porn

Comments are closed.

%d bloggers like this: