Integration with Google Charts

Read this tutorial to learn how to integrate the WebDataRocks reporting tool with Google Charts.

Supported chart types

WebDataRocks supports the following chart types:

  1. Area (demo)
  2. Bar (demo)
  3. Column (demo)
  4. Line (demo)
  5. Pie (demo)
  6. Sankey (demo)

If you need a chart that is not on the list, you can implement a custom logic of data processing in the options.prepareDataFunction parameter of googlecharts.getData().

To start a new Angular visualization project with WebDataRocks Pivot Table and Google Charts, follow the steps below.

Step 1. Add WebDataRocks to your project

Step 1.1. Complete the Quick start guide. Your code of the component with WebDatarocks should look similar to the following:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    }
    <app-wbr-pivot
     [toolbar]="true">
    </app-wbr-pivot>

    Step 1.2. Create a report for WebDataRocks — connect to the data source and define which fields should be displayed in rows, columns, and measures:

      import { Component} from "@angular/core";
      
      @Component({
        selector: "app-root",
        templateUrl: "./app.component.html",
        styleUrls: ["./app.component.css"],
      })
      export class AppComponent {
        report = {
          dataSource: {
            filename: "https://cdn.webdatarocks.com/data/data.csv",
          },
          slice: {
            rows: [
              {
                uniqueName: "Country",
              },
            ],
            columns: [
              {
                uniqueName: "Measures",
              },
            ],
            measures: [
              {
                uniqueName: "Price",
                aggregation: "sum",
              },
            ],
          },
        };
      }
      <app-wbr-pivot
       [toolbar]="true"
       [report]="report">
      </app-wbr-pivot>

      The fields you’ve specified in the report will be shown on the chart.

      Step 2. Get a reference to the WebDataRocks instance

      Some of WebDataRocks methods and events are needed to create a chart. Using a reference to the WebDataRocks instance, we can access WebDataRocks API.

      Import WebdatarocksComponent and get a reference to the <app-wbr-pivot> instance using a template variable and the @ViewChild decorator:

        import { Component, ViewChild } from "@angular/core";
        import { WebdatarocksComponent } from "@webdatarocks/ngx-webdatarocks";
        
        @Component({
          selector: "app-root",
          templateUrl: "./app.component.html",
          styleUrls: ["./app.component.css"],
        })
        export class AppComponent {
          @ViewChild("pivot") pivotRef!: WebdatarocksComponent;
        
          // ...
        }
        <app-wbr-pivot #pivot
         [toolbar]="true"
         [report]="report">
        </app-wbr-pivot>

        Now it’s possible to interact with the component through this.pivotRef.webdatarocks.

        Note. If you are using the legacy @webdatarocks/ng-webdatarocks wrapper, import WebdatarocksComponent from it.

        Step 3. Add Google Charts

        Step 3.1. Include Google Charts in src/index.html:

        <!-- Loading Google Charts -->
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

        The loader.js file provides a global google variable, which we will use to work with Google Charts.

        Step 3.2. In our Angular component, we now need to tell the TypeScript compiler that the google variable we will be using is declared in another file. It can be done with the declare keyword:

          import { Component, ViewChild } from "@angular/core";
          import { WebdatarocksComponent } from "@webdatarocks/ngx-webdatarocks";
          
          declare let google: any;
          
          @Component({
            selector: "app-root",
            templateUrl: "./app.component.html",
            styleUrls: ["./app.component.css"],
          })
          export class AppComponent {
            // ...
          }

          Step 3.3. Create a flag variable to know when the Google Charts library is ready to be used:

            googleChartsLoaded: boolean = false;

            Step 3.4. In the ngOnInit() hook, load the Google Visualization API and the corechart package:

              ngOnInit(): void {
                google.charts.load("current", {
                  packages: ["corechart", "bar"],
                });
              }

              Step 3.5. Add a callback to run when the Google Visualization API is loaded. In the callback handler, set the googleChartsLoaded flag to true:

                ngOnInit(): void {
                  google.charts.load("current", {
                    packages: ["corechart", "bar"],
                  });
                  google.charts.setOnLoadCallback(() => this.onGoogleChartsLoaded());
                }
                
                onGoogleChartsLoaded() {
                  this.googleChartsLoaded = true;
                }

                Step 3.6. In the HTML template of the component, create a <div> container for Google Charts with an id (e.g., googlechart-container):

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

                  If you run the project now, the chart won’t show any data because WebDataRocks is not integrated with Google Charts yet. We will connect them in the next step.

                  Step 4. Show the data from the pivot table on the chart

                  Step 4.1. Create a variable to store data for the chart (e.g., chartData):

                    chartData: any = [];

                    The chartData variable is now empty, but soon we’ll fill it with data from our component.

                    Step 4.2. Import the WebDataRocks Connector for Google Charts:

                      import "@webdatarocks/webdatarocks/webdatarocks.googlecharts.js";

                      The Connector provides the googlecharts.getData() method, which gets data from WebDataRocks and converts it to the format required for a specific chart type.

                      Step 4.3. If we call the googlecharts.getData() method before WebDataRocks is fully loaded, it will return an empty result. To know when WebDataRocks is ready to provide data for the chart, handle the reportcomplete event:

                        googleChartsLoaded: boolean = false;
                        // Add a flag variable to keep the state of the report
                        pivotTableReportComplete: boolean = false;
                        
                        // ...
                        
                        onReportComplete() {
                          // Unsubscribing from reportcomplete
                          // We need it only to track the initialization of WebDataRocks
                          this.pivotRef.webDataRocks.off("reportComplete");
                          this.pivotTableReportComplete = true;
                        }
                        <app-wbr-pivot #pivotRef
                         [toolbar]="true"
                         [report]="report"
                         (reportcomplete)="onReportComplete()">
                        </app-wbr-pivot>
                        <div id="googlechart-container"></div>

                        Now we know when the data is loaded and the report is ready.

                        Step 4.4. Let’s start creating a chart. A function to create a chart should be called only when the following conditions are met: 

                        • The Google Charts library is loaded (the googleChartsLoaded flag is true).
                        • The WebDataRocks report is ready (the pivotTableReportComplete flag is true).  

                        Since we don’t know which will happen first, we have to handle both cases. Modify onGoogleChartsLoaded() and onReportComplete() functions as follows:

                          onGoogleChartsLoaded() {
                            this.googleChartsLoaded = true;
                            // Handle the case when the report is complete before Google Charts is loaded 
                            if (this.pivotTableReportComplete) {
                              this.createChart();
                            }
                          }
                          
                          onReportComplete() {
                            // Unsubscribing from reportcomplete
                            // We need it only to track the initialization of WebDataRocks
                            this.pivotRef.webDataRocks.off("reportComplete");
                            this.pivotTableReportComplete = true;
                            // Handle the case when Google Charts is loaded before the report is complete
                            if (this.googleChartsLoaded) {
                              this.createChart();
                            }
                          }

                          Step 4.5. Now it’s time to implement the createChart() function. It will use the googlecharts.getData() method from the Connector:

                            createChart() {
                              this.pivotRef.webDataRocks.googlecharts?.getData(
                                {
                                  type: "column",
                                },
                                // Function called when data for the chart is ready
                                this.drawColumnChart.bind(this),
                                // Function called on report changes (filtering, sorting, etc.)
                                this.drawColumnChart.bind(this)
                              );
                            }

                            Step 4.6. Finally, implement the drawColumnChart() function:

                              drawColumnChart(_data: any) {
                                let data = google.visualization.arrayToDataTable(_data.data);
                                const columnChartContainer = document.getElementById("googlechart-container");
                                const chart = new google.visualization.ColumnChart(columnChartContainer);
                                chart.draw(data);
                              }

                              Notice the id of the columnChartContainer — it must match the id of a <div> created in step 3.6 (in our case, it is googlechart-container).

                              Step 5. Run the project

                              Run your project with the following command:

                              ng serve --open

                              If the page with WebDataRocks is not opened automatically, go to http://localhost:4200/ in the browser to see how the pivot table looks in combination with Google Charts.

                              To see what a real-time interaction is, try experimenting: filter the data, change the measures and the aggregation functions — the results are reflected on the chart at once.

                              To learn more about chart customization, please refer to the Google Charts Documentation.

                              Check out the full code

                              After completing this tutorial, the full code of the integration should look as follows:

                                import { Component, ViewChild } from "@angular/core";
                                import { WebdatarocksComponent } from "@webdatarocks/ngx-webdatarocks";
                                import "@webdatarocks/webdatarocks/webdatarocks.googlecharts.js";
                                
                                declare let google: any;
                                
                                @Component({
                                  selector: "app-root",
                                  templateUrl: "./app.component.html",
                                  styleUrls: ["./app.component.css"],
                                })
                                export class AppComponent {
                                  @ViewChild("pivot") pivotRef!: WebdatarocksComponent;
                                
                                  googleChartsLoaded: boolean = false;
                                  pivotTableReportComplete: boolean = false;
                                
                                  chartData: any = [];
                                
                                  report = {
                                    dataSource: {
                                      filename: "https://cdn.webdatarocks.com/data/data.csv",
                                    },
                                    slice: {
                                      rows: [
                                        {
                                          uniqueName: "Country",
                                        },
                                      ],
                                      columns: [
                                        {
                                          uniqueName: "Measures",
                                        },
                                      ],
                                      measures: [
                                        {
                                          uniqueName: "Price",
                                          aggregation: "sum",
                                        },
                                      ],
                                    },
                                  };
                                
                                  ngOnInit(): void {
                                    google.charts.load("current", {
                                      packages: ["corechart", "bar"],
                                    });
                                    google.charts.setOnLoadCallback(() => this.onGoogleChartsLoaded());
                                  }
                                
                                  onGoogleChartsLoaded() {
                                    this.googleChartsLoaded = true;
                                    // Handle the case when the report is complete before Google Charts is loaded
                                    if (this.pivotTableReportComplete) {
                                      this.createChart();
                                    }
                                  }
                                
                                  onReportComplete() {
                                    // Unsubscribing from reportcomplete
                                    // We need it only to track the initialization of WebDataRocks
                                    this.pivotRef.webDataRocks.off("reportComplete");
                                    this.pivotTableReportComplete = true;
                                    // Handle the case when Google Charts is loaded before the report is complete
                                    if (this.googleChartsLoaded) {
                                      this.createChart();
                                    }
                                  }
                                
                                  createChart() {
                                    this.pivotRef.webDataRocks.googlecharts?.getData(
                                      {
                                        type: "column",
                                      },
                                      // Function called when data for the chart is ready
                                      this.drawColumnChart.bind(this),
                                      // Function called on report changes (filtering, sorting, etc.)
                                      this.drawColumnChart.bind(this)
                                    );
                                  }
                                
                                  drawColumnChart(_data: any) {
                                    let data = google.visualization.arrayToDataTable(_data.data);
                                    const columnChartContainer = document.getElementById("googlechart-container");
                                    const chart = new google.visualization.ColumnChart(columnChartContainer);
                                    chart.draw(data);
                                  }
                                }
                                <app-wbr-pivot #pivot
                                 [toolbar]="true"
                                 [report]="report"
                                 (reportcomplete)="onReportComplete()">
                                </app-wbr-pivot>
                                <div id="googlechart-container"></div>
                                <!doctype html>
                                <html lang="en">
                                <head>
                                  <meta charset="utf-8">
                                  <title>WebDataRocks and Google Charts</title>
                                  <base href="/">
                                  <meta name="viewport" content="width=device-width, initial-scale=1">
                                  <link rel="icon" type="image/x-icon" href="favicon.ico">
                                  <!-- Loading Google Charts -->
                                  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
                                </head>
                                <body>
                                  <app-root></app-root>
                                </body>
                                </html>

                                See also