Sunday, 5 January 2020

google chart in spfx

To Show google chart in SPFX below are steps to follow

1. open the config.json file and add below enetry in external section

"externals": {
  "google": {
"path": "https://www.gstatic.com/charts/loader.js",
"globalName": "google"
  }
}
2. add below div tag in your html
<div id="pie-chart"></div>
3. create a google.d.ts file under the webpart folder inside src folder.
4. add below code in google.d.ts as a module

declare module "google" {
  interface IGoogle {
  charts: any;
  visualization: any;
  }
  var google: IGoogle;
  export = google;
}

5. now import the google module in webpart where you want to add graph

    import * as google from 'google';

6. add below code on OnInt method


public onInit(): Promise<void>
  {
google.charts.load("current", { packages: ["corechart"] });
return super.onInit();
  }

7. create a fucntion to LoadGoogleChart a chart
   
private LoadGoogleChart(arrayDataTable) {

// to add legend and first row in array
arrayDataTable.splice(0, 0, ['TaskList', 'Hours',{ role: 'annotation'}]);

     let data =google.visualization.arrayToDataTable(arrayDataTable);

const options = {
  title: 'My Daily Work',
  pieHole: 0.4,
};

const chart = new google.visualization.PieChart(document.getElementById('pie-chart'));
chart.draw(data, options);
  }

8. finally call your fucntion on button click or page load and pass the data in LoadGoogleChart() method as array
 
   private GraphData()
   {
  let graphDataArray=[];
  graphDataArray.push(['Work', 11]);
  graphDataArray.push(['Eat', 2]);
  graphDataArray.push(['Commute', 2]);
  graphDataArray.push(['Watch TV', 2]);
  graphDataArray.push(['Sleep', 7]);
  google.charts.setOnLoadCallback(webpart.LoadGoogleChart(graphDataArray));
   }

No comments:

Post a Comment