21

Creating a Sales Dashboard Using Angular and Google Charts

 5 years ago
source link: https://www.tuicool.com/articles/hit/ueyQjeM
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

fA36r2i.jpg!web

In this tutorial, you'll learn how to create a sales dashboard using Angular and Google Charts. The tutorial assumes that you are familiar with basic Angular and JavaScript.

The source code from this tutorial is available on GitHub .

Getting Started With an Angular App

For getting started with Angular, you need to install Angular CLI using Node Package Manager (npm):

npm install -g @angular/cli

Once you have the Angular CLI installed, you can use it to create an Angular boilerplate project.

ng new angular-sales-dashboard

The command above creates the Angular project boilerplate code.

Include Google Charts Script In Your Angular App

You'll be using Google Charts to create the dashboard in this Angular app. Let's start by adding the Google Charts script files into our Angular app.

https://www.gstatic.com/charts/loader.js

Download the script above into the assets/js folder or use it directly by including it in the angular.json file.

Include the loader.js script in the script section of the angular.json file.

"scripts": [
    "src/assets/js/loader.js"
]

You'll be using the Google Charts script to create different types of charts. So, it's better if you define it inside an Angular service module. This service module can be used to access Google Charts all across the Google Charts module.

Creating The Google Charts Service Module

Let's start by creating a module for Google Charts. From the command prompt type in the following command:

ng g module google-chart

This creates a module called GoogleChartModule inside the src/app/google-chart/google-chart.module.ts file. Here is how it looks :

import { NgModule } from '@angular/core';  
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  exports: [],
  providers : []
})
export class GoogleChartModule { }

Inside the google-chart module, create another module called service .

ng g module google-chart/service

This will create a service folder inside the google-chart folder. This service folder contains the ServiceModule file called service.module.ts . Here is how it looks :

import { NgModule } from '@angular/core';  
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class ServiceModule { }

ServiceModule will have the Angular service which will be utilized to access the Google Charts library.

Let's create the Angular service inside the service module.

ng g service google-chart/service/google-chart

The command above creates a service file called google-chart.service.ts .

Declare a global variable called google above the @Injectable decorator. It refers to the Google Charts library script included in the Angular app.

declare  var  google:  any;

Next, define a private variable google inside the GoogleChartService service. Set its value to the global google variable and return it with the help of a method inside the GoogleChartService class.

Here is how the google-chart.service.ts file looks:

import { Injectable } from '@angular/core';  
import { ServiceModule } from './service.module';

declare var google: any;

@Injectable({
  providedIn: ServiceModule
})
export class GoogleChartService {  
  private google : any;
  constructor() { 
    this.google = google;
  }

  getGoogle(){
    return this.google;
  }
}

As you can notice in the code above, providedIn in the GoogleChartService is being set to the ServiceModule . It indicates that the GoogleChartService is available only inside the ServiceModule .

Now, in order to use the Service module inside the GoogleChartModule , you only need to import it inside the google-chart.module.ts file.

import { NgModule } from '@angular/core';  
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    ServiceModule
  ],
  exports: [],
  providers : []
})
export class GoogleChartModule { }

Creating The Line Chart Component

You'll be using GoogleChartService for creating the line chart.

ng g component google-chart/line-chart

This creates a LineChartComponent inside google-chart/line-component .The line-chart.component.ts file should look like this:

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

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {

  constructor() { 
  }

  ngOnInit() {
  }
}

Let's import the GoogleChartService inside the line-chart.component.ts file.

import { GoogleChartService } from  '../service/google-chart.service';

And reference it inside the component constructor method.

constructor(private gChartService : GoogleChartService) { 

}

Now, let's reference the Google Charts library to a private variable and use it to initialize the core packages for creating the line chart inside the LineChartComponent constructor method.

private gLib: any;

  constructor(private gChartService : GoogleChartService) { 
    this.gLib = this.gChartService.getGoogle();
    this.gLib.charts.load('current', {'packages':['corechart','table']});
    this.gLib.charts.setOnLoadCallback(this.drawChart.bind(this));
  }

Once the Google Charts library packages have been loaded, a callback method called drawChart will be triggered. This drawChart method will contain the code to create the line chart. Here is how this method should look like:

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

    let chart = new this.gLib.visualization.LineChart(document.getElementById('divLineChart'));

    chart.draw(data);
  }

Note:For the sake of this tutorial, you are using dummy hard-coded data. You can replace the data with a REST API endpoint or database service call as per your project requirement.

Vz6fuiq.jpg!web

As seen in the code snippet above, the drawChart method uses the Google Charts library referenced using the gLib variable to create the datatable. Once the datatable is prepared, you create a new chart using the LineChart method and passing in the container div for showing the line chart. Lastly, you draw the chart by passing the data to the draw method. The line-chart.component.ts file should look like this:

import { Component, OnInit } from '@angular/core';  
import { GoogleChartService } from '../service/google-chart.service';

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {

  private gLib: any;

  constructor(private gChartService : GoogleChartService) { 
    this.gLib = this.gChartService.getGoogle();
    this.gLib.charts.load('current', {'packages':['corechart','table']});
    this.gLib.charts.setOnLoadCallback(this.drawChart.bind(this));
  }

  ngOnInit() {

  }

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

    let chart = new this.gLib.visualization.LineChart(document.getElementById('divLineChart'));

    chart.draw(data);
  }

}

And the line-chart.component.html file should look like so:

<div  id="divLineChart">

</div>

Using The Line Chart Component

You can use the LineChartComponent by exporting it from the GoogleChartModule . Add the LineChartComponent to the exports in the google-chart.module.ts file:

import { NgModule } from '@angular/core';  
import { CommonModule } from '@angular/common';  
import { LineChartComponent } from './line-chart/line-chart.component';  
import { ServiceModule } from './service/service.module';

@NgModule({
  declarations: [LineChartComponent],
  imports: [
    CommonModule,
    ServiceModule
  ],
  exports: [LineChartComponent],
  providers : []
})
export class GoogleChartModule { }

Now, you can use the LineChartComponent using the selector app-line-chart .

Modify the app.component.html file to include the line chart component.

<app-line-chart></app-line-chart>

Save the above changes and start the Angular app. You'll be able to see the Line chart rendered in the Angular app.

Ij2UNvu.png!web

Creating the Pie Chart Component

Let's create the pie chart component for displaying some data in the form of a pie chart. Start by creating a pie-chart component inside the google-chart module.

ng g component google-chart/pie-chart

Next, let's import the GoogleChartService inside the PieChartComponent and load the required packages for creating the pie chart inside the constructor method. Here is how it looks:

import { Component, OnInit } from '@angular/core';  
import { GoogleChartService } from '../service/google-chart.service';

@Component({
  selector: 'app-pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrls: ['./pie-chart.component.css']
})
export class PieChartComponent implements OnInit {

  private gLib: any;

  constructor(private gChartService : GoogleChartService) { 
    this.gLib = this.gChartService.getGoogle();
    this.gLib.charts.load('current', {'packages':['corechart','table']});
    this.gLib.charts.setOnLoadCallback(this.drawChart.bind(this));
  }

  ngOnInit() {

  }

}

You also need to define the drawChart callback method which is handling the processing of data and drawing the pie chart.

Here is how the pie-chart.component.ts file looks:

import { Component, OnInit } from '@angular/core';  
import { GoogleChartService } from '../service/google-chart.service';

@Component({
  selector: 'app-pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrls: ['./pie-chart.component.css']
})
export class PieChartComponent implements OnInit {

  private gLib: any;

  constructor(private gChartService : GoogleChartService) { 
    this.gLib = this.gChartService.getGoogle();
    this.gLib.charts.load('current', {'packages':['corechart','table']});
    this.gLib.charts.setOnLoadCallback(this.drawChart.bind(this));
  }

  ngOnInit() {

  }

  private drawChart(){
    let chart = new this.gLib.visualization.PieChart(document.getElementById('divPieChart'));
    let data = new this.gLib.visualization.DataTable();
    data.addColumn('string', 'Accessories');
    data.addColumn('number', 'Quantity');
    data.addRows([
      ['Computers', 3],
      ['Hard Drives', 6],
      ['Printers', 4],
      ['Monitors', 5],
      ['RAM', 2]
    ]);

    let options = {'title':'Sales Info'};

    chart.draw(data, options);
  }

}

Once your PieChartComponent is ready, you can export the component from the GoogleChartModule . The google-chart.module.ts should look similar to this:

import { NgModule } from '@angular/core';  
import { CommonModule } from '@angular/common';  
import { LineChartComponent } from './line-chart/line-chart.component';  
import { ServiceModule } from './service/service.module';  
import { PieChartComponent } from './pie-chart/pie-chart.component';


@NgModule({
  declarations: [LineChartComponent, PieChartComponent],
  imports: [
    CommonModule,
    ServiceModule
  ],
  exports: [LineChartComponent, PieChartComponent],
  providers : []
})
export class GoogleChartModule { }

So, the PieChartComponent is ready to use. You'll use it along with LineChartComponent inside AppComponent to create the dashboard.

VzeMVjq.jpg!web

Creating the Table Chart Component

You'll also be creating a table chart component for rendering the data in tabular format. Let's create a table-chart component inside the google-chart module.

ng g component google-chart/table-chart

The code for this component is quite similar to the two components you created earlier. It also uses the GoogleChartService for accessing the Google library and creates the tabular chart. Here is how the table-chart.component.ts file looks :

import { Component, OnInit } from '@angular/core';  
import { GoogleChartService } from '../service/google-chart.service';

@Component({
  selector: 'app-table-chart',
  templateUrl: './table-chart.component.html',
  styleUrls: ['./table-chart.component.css']
})
export class TableChartComponent implements OnInit {

  private gLib: any;

  constructor(private gChartService : GoogleChartService) { 
    this.gLib = this.gChartService.getGoogle();
    this.gLib.charts.load('current', {'packages':['corechart','table']});
    this.gLib.charts.setOnLoadCallback(this.drawChart.bind(this));
  }
  ngOnInit() {

  }

  private drawChart(){
    let chart = new this.gLib.visualization.Table(document.getElementById('divTableChart'));
    let data = new this.gLib.visualization.DataTable();

    data.addColumn('string', 'Year');
    data.addColumn('number', 'Sales');
    data.addColumn('number', 'Expenses');

    data.addRows([
      ['2004', 1000, 400],
      ['2005', 1170, 460],
      ['2006', 660, 1120],
      ['2007', 1030, 540]
    ]);

    let options = {'title':'Sales Tabular Data',
                       'width': '100%',
                       'height': '100%'};
    chart.draw(data, options);
  }

}

Export the TableChartComponent inside the GoogleChartModule .

// google-chart.module.ts

import { NgModule } from '@angular/core';  
import { CommonModule } from '@angular/common';  
import { LineChartComponent } from './line-chart/line-chart.component';  
import { ServiceModule } from './service/service.module';  
import { PieChartComponent } from './pie-chart/pie-chart.component';  
import { TableChartComponent } from './table-chart/table-chart.component';

@NgModule({
  declarations: [LineChartComponent, PieChartComponent, TableChartComponent],
  imports: [
    CommonModule,
    ServiceModule
  ],
  exports: [LineChartComponent, PieChartComponent, TableChartComponent],
  providers : []
})
export class GoogleChartModule { }

Now, since you have the required components ready, you can use it to create the sales dashboard.

Creating The Sales Dashboard

You'll be using Bootstrap for styling the dashboard. Let's install it using npm.

npm install bootstrap --save

Once you have Bootstrap installed in your app, reference the Bootstrap style in the angular.json file for getting Bootstrap styles all across the Angular app.

"styles": [
   "src/styles.css",
   "node_modules/bootstrap/dist/css/bootstrap.min.css"
]

Add the following HTML code to app.component.html for rendering all the charts in the dashboard.

<div class="container">  
    <div class="header">
        <h2>
            Angular Sales Dashboard
        </h2>
    </div>

    <div class="row">
        <div class="col-7">
            <app-line-chart></app-line-chart>
        </div>
        <div class="col-5">
            <app-pie-chart></app-pie-chart>
        </div>
    </div>
    <div class="row">
        <div class="col-12">
            <app-table-chart></app-table-chart>
        </div>
    </div>
  </div>

Save the above changes and restart the Angular app. You will have the Angular sales dashboard rendered in the browser.

f6fUVve.png!web

Wrapping It Up

In this tutorial, you learned how to create a basic sales dashboard using Angular 7 and the Google Charts library. You learned how to create modules in Angular and how to use it in other modules. This may be useful to incorporate in your own future projects.

Lastly, if you want to learn how you can secure your Angular source code against theft and reverse-engineering, be sure to checkour guide.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK