How To Create Google Line Chart In Angular

In this post, you will discover how to add a Line chart to Google Charts.

When looking for trends in data over time, use a line chart. Get monthly, quarterly, or annual trends in sales or profit margins, for instance.

Step 1:

Create a New Application

ng new LineChart

Step 2:

Install Following Package

npm install angular-google-charts

Step 3:

Include the GoogleChartsModule in your app. The module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { GoogleChartsModule } from 'angular-google-charts';
   
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    GoogleChartsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4:

Insert the following code into your app.component.ts file.

import { Component, OnInit } from '@angular/core';

declare let google: any;

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular';

  ngOnInit() {
    this.drawChart();
  }
  drawChart() {
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2004',  1000,      400],
        ['2005',  1170,      460],
        ['2006',  660,       1120],
        ['2007',  1030,      540]
      ]);

      var options = {
        title: 'Company Performance',
        curveType: 'function',
        legend: { position: 'bottom' }
      };

      var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

      chart.draw(data, options);
    }
  }
}

Step 5 :

Insert the following code into your app.component.html file

<div #chartDiv id="curve_chart"></div>

Step 6:

Run your Application using the following code

ng serve

Output :

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories