How do I put a Google Chart in Angular 4

Viewed 17545

How do you integrate a google chart in an angular 4 application?

I read the answer to the SO question here, but I believe it's incomplete. Basically, I'm attempting the same strategy as the previous answer, using a GoogleChartComponent and another component that extends it. Two errors arise, the first is a missing call to super() for the child component and the second is the call to "new" in this code

  createBarChart(element: any): any {
      return new google.visualization.BarChart(element);
  }

I'm getting the error "google.visualization.BarChart is not a constructor".

I see one of the comments also mentions the use of <ng-content> for data projection but it isn't clearly outlined.

In trying to ask a "good" question, here is my GoogleChartComponent:

export class GoogleChartComponent implements OnInit {
  private static googleLoaded: any;
  constructor() {
    console.log('Here is GoogleChartComponent');
  }

  getGoogle() {
    return google;
  }

  ngOnInit() {
    console.log('ngOnInit');
    if (!GoogleChartComponent.googleLoaded) {
      GoogleChartComponent.googleLoaded = true;
      google.charts.load('current', {
        'packages': ['bar']
      });
      google.charts.setOnLoadCallback(() => this.drawGraph());
    }
  }

  drawGraph() {
      console.log('DrawGraph base class!!!! ');
  }

  createBarChart(element: any): any {
      return new google.visualization.BarChart(element);
  }

  createDataTable(array: any[]): any {
      return google.visualization.arrayToDataTable(array);
  }
}

And my child component that extends it:

@Component({
  selector: 'app-bitcoin-chart',
  template: `
   <div id="barchart_material" style="width: 700px; height: 500px;"></div>
  `,
  styles: []
})
export class BitcoinChartComponent extends GoogleChartComponent  {
 private options;
  private data;
  private chart;
  // constructor() {
  //   super();
  //   console.log('Bitcoin Chart Component');
  // }
  drawGraph() {
    console.log('Drawing Bitcoin Graph');
    this.data = this.createDataTable([
     ['Price', 'Coinbase', 'Bitfinex', 'Poloniex', 'Kraken'],
     ['*', 1000, 400, 200, 500]
    ]);

    this.options = {
     chart: {
                    title: 'Bitcoin Price',
                    subtitle: 'Real time price data across exchanges',
                },
                bars: 'vertical' // Required for Material Bar Charts.
    };

    this.chart = this.createBarChart(document.getElementById('barchart_material'));
    this.chart.draw(this.data, this.options);
  }
}
2 Answers
Related