How do I put a Google Chart in Angular 4

前端 未结 2 751
灰色年华
灰色年华 2021-02-08 16:31

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 t

2条回答
  •  时光说笑
    2021-02-08 17:09

    I believe there is better way to integrate Google Chart in Angular 4. Library ng2-google-charts already has GoogleChartComponent. Link to npm page describes pretty well how to use it. Below is example of component:

    import {Component, ViewEncapsulation, OnInit} from '@angular/core';
    import {Component, ViewEncapsulation, OnInit} from '@angular/core';
    import {Component, ViewEncapsulation, OnInit} from '@angular/core';
    import {ViewChild} from '@angular/core';
    
    import {GoogleChartComponent} from 'ng2-google-charts';
    
    // needed for advanced usage of ng2-google-charts
    import {HostListener} from '@angular/core';
    
    @Component({
      selector: '[your-widget]',
      templateUrl: './your-widget.html',
      encapsulation: ViewEncapsulation.None
    })
    export class YourWidget implements OnInit {
    
      // type GoogleChartComponent and import for it can be ommited
      @ViewChild('your_chart') chart: GoogleChartComponent;
    
      // shows spinner while data is loading
      showSpinner: boolean;
    
      public chartData = {
        chartType: 'AnyChartType', // your type
        dataTable: [
          ['Col1', 'Col2']
        ],
        options: {}
      };
    
      constructor() {
      }
    
      ngOnInit(): void {
    
        this.showSpinner = true;
        this.yourService.getData()
              .subscribe((data) => {
                //this.data = data;
                this.processYourData();
                this.showSpinner = false;
            });
          }
    
      private processYourData() {
      }
    
      // advanced usage of chart
      //   in this case redraw function on window:resize event
      @HostListener('window:resize', ['$event'])
      onWindowResize(event: any) {
        // console.log(event.target.innerWidth);
        // Make sure you don't call redraw() in ngOnInit()
        //   - chart would not be initialised by that time, and
        //   - this would cause chart being drawn twice
        this.chart.redraw(); 
      }
    }
    

    And your markup would look like this:

    Widget Title

提交回复
热议问题