How to use Google Charts in .Net core application using Typescript

Google charts is a wonderful library when it comes to provide visualization to your data. This library has rich gallery of type of charts you can use for visualization. It is a Javascript library. As more and more developers are incorporating Typescript into their .Net core projects, you would want to know how to use Google Charts library in Typescript.

Google has done a good job of providing a getting started with Google Charts page on their site. For sake of completion, I will inlcude list of basic steps in using Google Charts here as well.

  • Include reference of Javascript library on your page
  • Add an anchor HTML element on your page where chart will be drawn
  • Prepare that data that needs visualization. Google has a very specific requirement about it. You can get the data from your WebApi in JSON format and then project it to Google's object requirements.
  • Use specific chart API for type of chart that you want to draw

When it comes to using a Javascript library in your Typescript code, you will need to include typings for the definitions used in the Javascript library. To include Google Chart library typings, use npm to install the type defintions.

npm install --save @types/google.visualization

This command will add type definitions in @types folder in your project. That is all that you will need to do. Following code snippet shows how I used this library to create data visualization in our HomeRP® project.

renderMonthlyConsumptionReport(data: InventoryAdjustmentByPeriod[]) {
        google.charts.load('current', { 'packages': ["corechart"] });
        google.charts.setOnLoadCallback(() => {
            const chartData = new google.visualization.DataTable();
            chartData.addColumn("string", "Month Of");
            chartData.addColumn("number", "Consumed");
            const chartOptions = { legend: { position: "none" as "none" } };
            for (let i = 0; i < data.length; i++) {
                chartData.addRow([this.getMonthName(data[i].month), Math.abs(data[i].itemsAdjusted)]);
            const chart = new google.visualization.ColumnChart(this.monthlyConsumptionChart);
            chart.draw(chartData, chartOptions);

I get the data from WebApi as JSON array. You have to create DataTable object and then add the data in that table. First you add the columns and type of data included in that column. After that you will add each row of the data. Google Chart library will read this DataTable object and draw the chart library.

If you have any questions, feel free to drop me a line.




19.7 °C / 67.5 °F

weather conditions Clouds

Monthly Posts

Blog Tags