Create Charts In Angular 7 Application Using Chart.js

In this article, we will explore the process of integration of chart.js library in an Angular application.

Chart.js is an open source JavaScript library for creating charts. Chart.js makes it easier to draw different types of charts like line chart, bar chart, doughnut chart, area chart etc. In this article, we will create a line chart, bar chart, pie chart, polar area using chart.js, Web API, and Angular 7. Learn more about chart.js.

Prerequisites

  • We should have a basic knowledge of Angular and Web API.
  • Visual Studio Code can be installed
  • Visual Studio
  • SQL Server Management Studio

Project Implementation steps

  1. Database 
  2. Web API to fetch data from the database
  3. Angular 7 project 

Step 1 

Open SQL Server Management Studio and create a table Tblplayer and add some demo data into this table.
  1. CREATE TABLE [dbo].[Tblplayer](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [PlayerName] [varchar](50) NULL,  
  4.     [Run] [varchar](50) NULL,  
  5. PRIMARY KEY CLUSTERED   
  6. (  
  7.     [Id] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]  
  10.   
  11. GO  
  12. SET ANSI_PADDING OFF  
  13. GO  
  14. SET IDENTITY_INSERT [dbo].[Tblplayer] ON   
  15.   
  16. GO  
  17. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (1, N'Rohit Sharma', N'59')  
  18. GO  
  19. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (2, N'Sikar Dhwan', N'19')  
  20. GO  
  21. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (3, N'Virat Kholi', N'79')  
  22. GO  
  23. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (4, N'Rishabh Panth', N'99')  
  24. GO  
  25. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (5, N'Ms Dhoni', N'119')  
  26. GO  
  27. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (6, N'H Pandya', N'9')  
  28. GO  
  29. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (7, N'B kumar', N'51')  
  30. GO  
  31. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (8, N'K Yadav', N'11')  
  32. GO  
  33. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (9, N'Chahal', N'4')  
  34. GO  
  35. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (10, N'Bumrah', N'9')  
  36. GO  
  37. INSERT [dbo].[Tblplayer] ([Id], [PlayerName], [Run]) VALUES (11, N'Shami', N'5')  
  38. GO  
  39. SET IDENTITY_INSERT [dbo].[Tblplayer] OFF  
  40. GO  

Step 2

Open Visual Studio and create a new project.

Go to File > New > Project.

 
Create Charts In Angular 7 Application Using Chart.js

Select Web API as a Template and click on the OK button.

Create Charts In Angular 7 Application Using Chart.js

Step 3

Right-click on the Models folder from Solution Explorer and go to Add >> New Item >> Data.
 
Create Charts In Angular 7 Application Using Chart.js
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
Create Charts In Angular 7 Application Using Chart.js
 
Select "EF designer from the database" and click the "Next" button.
 
Create Charts In Angular 7 Application Using Chart.js
 
Add the connection properties and select the database name on the next page. Then, click OK.
 
Create Charts In Angular 7 Application Using Chart.js
 
Check Table checkboxes. The internal options will be selected by default. Now, click the "Finish" button.
 
Create Charts In Angular 7 Application Using Chart.js
 
Our data model is created now.
 
Step 4
 
Right-click on the Controllers folder and add a new controller. Name it as "Chartscontroller".
 
Add the following namespace in the Charts Controller.
 
using GraphDemo.Models;
 
Add a new method to fetch data from the database.
  1. [Route("GetCharts")]  
  2.         [HttpGet]  
  3.         public object GetChartsData()  
  4.         {  
  5.             ChartsDemoEntities DB = new ChartsDemoEntities();  
  6.             return Json(DB.Tblplayers.ToList());  
  7.         }  
Complete the Chartscontroller code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using GraphDemo.Models;  
  8.   
  9. namespace GraphDemo.Controllers  
  10. {  
  11.     [RoutePrefix("API/Charts")]  
  12.   
  13.     public class ChartsController : ApiController  
  14.     {  
  15.         [Route("GetCharts")]  
  16.         [HttpGet]  
  17.         public object GetChartsData()  
  18.         {  
  19.             ChartsDemoEntities DB = new ChartsDemoEntities();  
  20.             return Json(DB.Tblplayers.ToList());  
  21.         }  
  22.     }  
  23. }  
Step 5
 
Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors and install the "Microsoft.Asp.Net.WebApi.Cors" package.
 
Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");    
  2. config.EnableCors(cors);  

Angular 7 Project

 
Step 1
 
Create an Angular 7 project with the name "chartjsdemo" by using the following command.
 
ng new chartjsdemo
 
Step 2
 
Open Visual Studio Code, open the newly created project, and add Chart.js to this project by using the following command.
 
npm install chart.js --save
 
Step 3

Now, create 5 components for the bar chart, line chart, doughnut chart, pie Chart respectively. To create the components, open terminal and use the following commands.
 
ng g c linechart 
ng g c barchart
ng g c doughnut
ng g c piechart 
ng g c polararea
 
Create Charts In Angular 7 Application Using Chart.js
 
Step 4
 
Create a class named "Data" by using the following command.
 
ng g class Data
 
Add the following properties in the Data class.
  1. export class Data {  
  2.     PlayerName :string;  
  3.     Run:string;  
  4.   }  
Step 5 - Line Chart
 
Open linechart.component.ts file and add the required chartjs module, class, and other required modules.
  1. import { Chart } from 'chart.js';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { Data } from '../../app/Data';  
linechart.component.ts file
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Chart } from 'chart.js';  
  3. import { HttpClient } from '@angular/common/http';  
  4. import { Data } from '../../app/Data';  
  5. @Component({  
  6.   selector: 'app-linechart',  
  7.   templateUrl: './linechart.component.html',  
  8.   styleUrls: ['./linechart.component.css']  
  9. })  
  10. export class LinechartComponent implements OnInit {  
  11.   
  12.   url = 'http://localhost:58617/API/Charts/GetCharts';  
  13.   data: Data[];  
  14.   Player = [];  
  15.   Run = [];  
  16.   Linechart = [];  
  17.   constructor(private httpClient: HttpClient) { }  
  18.   
  19.   ngOnInit() {  
  20.     this.httpClient.get(this.url).subscribe((result: Data[]) => {  
  21.       result.forEach(x => {  
  22.         this.Player.push(x.PlayerName);  
  23.         this.Run.push(x.Run);  
  24.       });  
  25.       this  
  26.       this.Linechart = new Chart('canvas', {  
  27.         type: 'line',  
  28.         data: {  
  29.           labels: this.Player,  
  30.   
  31.           datasets: [  
  32.             {  
  33.               data: this.Run,  
  34.               borderColor: '#3cb371',  
  35.               backgroundColor: "#0000FF",  
  36.             }  
  37.           ]  
  38.         },  
  39.         options: {  
  40.           legend: {  
  41.             display: false  
  42.           },  
  43.           scales: {  
  44.             xAxes: [{  
  45.               display: true  
  46.             }],  
  47.             yAxes: [{  
  48.               display: true  
  49.             }],  
  50.           }  
  51.         }  
  52.       });  
  53.     });  
  54.   }  
  55. }  
Create Charts In Angular 7 Application Using Chart.js
 
Now, open linechart.component.html file and add the following HTML.
  1. <div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  2.   <canvas id="canvas">{{ Linechart }}</canvas>    
  3. </div>    
Step 6 - Bar Chart
 
Open barchart.component.ts file and add the following code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Chart } from 'chart.js';  
  3. import { HttpClient } from '@angular/common/http';  
  4. import { Data } from '../../app/Data';  
  5. @Component({  
  6.   selector: 'app-barchart',  
  7.   templateUrl: './barchart.component.html',  
  8.   styleUrls: ['./barchart.component.css']  
  9. })  
  10. export class BarchartComponent implements OnInit {  
  11.   data: Data[];  
  12.   url = 'http://localhost:58617/API/Charts/GetCharts';  
  13.   Player = [];  
  14.   Run = [];  
  15.   barchart = [];  
  16.   constructor(private http: HttpClient) { }  
  17.   
  18.   ngOnInit() {  
  19.     this.http.get(this.url).subscribe((result: Data[]) => {  
  20.       result.forEach(x => {  
  21.         this.Player.push(x.PlayerName);  
  22.         this.Run.push(x.Run);  
  23.       });  
  24.       this  
  25.       this.barchart = new Chart('canvas', {  
  26.         type: 'bar',  
  27.         data: {  
  28.           labels: this.Player,  
  29.           datasets: [  
  30.             {  
  31.               data: this.Run,  
  32.               borderColor: '#3cba9f',  
  33.               backgroundColor: [  
  34.                 "#3cb371",  
  35.                 "#0000FF",  
  36.                 "#9966FF",  
  37.                 "#4C4CFF",  
  38.                 "#00FFFF",  
  39.                 "#f990a7",  
  40.                 "#aad2ed",  
  41.                 "#FF00FF",  
  42.                 "Blue",  
  43.                 "Red",  
  44.                 "Blue"  
  45.               ],  
  46.               fill: true  
  47.             }  
  48.           ]  
  49.         },  
  50.         options: {  
  51.           legend: {  
  52.             display: false  
  53.           },  
  54.           scales: {  
  55.             xAxes: [{  
  56.               display: true  
  57.             }],  
  58.             yAxes: [{  
  59.               display: true  
  60.             }],  
  61.           }  
  62.         }  
  63.       });  
  64.     });  
  65.   }  
  66. }  
Open barchart.component.html file and add the following HTML.
  1. <div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  2.   <canvas id="canvas"></canvas>    
  3. </div>   
Step 7 - Pie Chart
 
Open piechart.component.ts file and add the following code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Chart } from 'chart.js';  
  3. import { HttpClient } from '@angular/common/http';  
  4. import { Data } from '../../app/Data';  
  5. @Component({  
  6.   selector: 'app-piechart',  
  7.   templateUrl: './piechart.component.html',  
  8.   styleUrls: ['./piechart.component.css']  
  9. })  
  10. export class PiechartComponent implements OnInit {  
  11.     title = 'app';  
  12.     data: Data[];  
  13.     url = 'http://localhost:58617/API/Charts/GetCharts';  
  14.     Player = [];  
  15.     Run = [];  
  16.     chart = [];  
  17.     constructor(private httpClient: HttpClient) { }  
  18.     
  19.     ngOnInit() {  
  20.       this.httpClient.get(this.url).subscribe((result: Data[]) => {  
  21.         result.forEach(x => {  
  22.           this.Player.push(x.PlayerName);  
  23.           this.Run.push(x.Run);  
  24.         });  
  25.         this  
  26.         this.chart = new Chart('canvas', {  
  27.           type: 'pie',  
  28.           data: {  
  29.             labels: this.Player,  
  30.             datasets: [  
  31.               {  
  32.                 data: this.Run,  
  33.                 borderColor: '#3cba9f',  
  34.                 backgroundColor: [  
  35.                   "#3cb371",  
  36.                   "#0000FF",  
  37.                   "#9966FF",  
  38.                   "#4C4CFF",  
  39.                   "#00FFFF",  
  40.                   "#f990a7",  
  41.                   "#aad2ed",  
  42.                   "#FF00FF",  
  43.                   "Blue",  
  44.                   "Red",  
  45.                   "Blue"  
  46.                 ],  
  47.                 fill: true  
  48.               }  
  49.             ]  
  50.           },  
  51.           options: {  
  52.             legend: {  
  53.               display: true  
  54.             },  
  55.             scales: {  
  56.               xAxes: [{  
  57.                 display: true  
  58.               }],  
  59.               yAxes: [{  
  60.                 display: true  
  61.               }],  
  62.             }  
  63.           }  
  64.         });  
  65.       });  
  66.     }  
  67.   }  
Open piechart.component.html file and add the following HTML.
  1. <div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  2.   <canvas id="canvas"></canvas>    
  3. </div>   
Step 8 - Doughnut Chart
 
Open doughnut.component.ts file and add the following code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Chart } from 'chart.js';  
  3. import { HttpClient } from '@angular/common/http';  
  4. import { Data } from '../../app/Data';  
  5. @Component({  
  6.   selector: 'app-doughnut',  
  7.   templateUrl: './doughnut.component.html',  
  8.   styleUrls: ['./doughnut.component.css']  
  9. })  
  10. export class DoughnutComponent implements OnInit {  
  11.     data: Data[];  
  12.     url = 'http://localhost:58617/API/Charts/GetCharts';  
  13.     Player = [];  
  14.     Run = [];  
  15.     chart = [];  
  16.     constructor(private httpClient: HttpClient) { }  
  17.     ngOnInit() {  
  18.       this.httpClient.get(this.url).subscribe((result: Data[]) => {  
  19.         result.forEach(x => {  
  20.           this.Player.push(x.PlayerName);  
  21.           this.Run.push(x.Run);  
  22.         });  
  23.         this  
  24.         this.chart = new Chart('canvas', {  
  25.           type: 'doughnut',  
  26.           data: {  
  27.             labels: this.Player,  
  28.             datasets: [  
  29.               {  
  30.                 data: this.Run,  
  31.                 borderColor: '#3cba9f',  
  32.                 backgroundColor: [  
  33.                   "#3cb371",  
  34.                   "#0000FF",  
  35.                   "#9966FF",  
  36.                   "#4C4CFF",  
  37.                   "#00FFFF",  
  38.                   "#f990a7",  
  39.                   "#aad2ed",  
  40.                   "#FF00FF",  
  41.                   "Blue",  
  42.                   "Red",  
  43.                   "Blue"  
  44.                 ],  
  45.                 fill: true  
  46.               }  
  47.             ]  
  48.           },  
  49.           options: {  
  50.             legend: {  
  51.               display: true  
  52.             },  
  53.             scales: {  
  54.               xAxes: [{  
  55.                 display: false  
  56.               }],  
  57.               yAxes: [{  
  58.                 display: true  
  59.               }],  
  60.             }  
  61.           }  
  62.         });  
  63.       });  
  64.     }  
  65.   }  
Open doughnut.component.html file and add the following HTML.
  1. <div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  2.   <canvas id="canvas"></canvas>    
  3. </div>   
Step 9 - Polararea Chart
 
Open polararea.component.ts file and add the  following code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Chart } from 'chart.js';  
  3. import { HttpClient } from '@angular/common/http';  
  4. import { Data } from '../../app/Data';  
  5. @Component({  
  6.   selector: 'app-polararea',  
  7.   templateUrl: './polararea.component.html',  
  8.   styleUrls: ['./polararea.component.css']  
  9. })  
  10. export class PolarareaComponent implements OnInit {  
  11.   
  12.     url = 'http://localhost:58617/API/Charts/GetCharts';  
  13.     data: Data[];  
  14.     Player = [];  
  15.     Run = [];  
  16.     Linechart = [];  
  17.     constructor(private httpClient: HttpClient) { }  
  18.   
  19.     ngOnInit() {  
  20.       this.httpClient.get(this.url).subscribe((result: Data[]) => {  
  21.         result.forEach(x => {  
  22.           this.Player.push(x.PlayerName);  
  23.           this.Run.push(x.Run);  
  24.         });  
  25.         this  
  26.         this.Linechart = new Chart('canvas', {  
  27.           type: 'polarArea',  
  28.           data: {  
  29.             labels: this.Player,  
  30.      
  31.             datasets: [  
  32.               {  
  33.                 data: this.Run,  
  34.                 borderColor: '#3cb371',  
  35.                 backgroundColor: [  
  36.                   "#3cb371",  
  37.                   "#0000FF",  
  38.                   "#9966FF",  
  39.                   "#4C4CFF",  
  40.                   "#00FFFF",  
  41.                   "#f990a7",  
  42.                   "#aad2ed",  
  43.                   "#FF00FF",  
  44.                   "Blue",  
  45.                   "Red",  
  46.                   "Blue"  
  47.                 ],  
  48.               }  
  49.             ],  
  50.           },  
  51.           options: {  
  52.             legend: {  
  53.               display: false  
  54.             },  
  55.             scales: {  
  56.               xAxes: [{  
  57.                 display: false  
  58.               }],  
  59.               yAxes: [{  
  60.                 display: true  
  61.               }],  
  62.             }  
  63.           }  
  64.         });  
  65.       });  
  66.     }  
  67.   }  
Open polararea.component.html file and add the following HTML.
  1. <div class="chart-container" style="position: relative; height:40vh; width:70vw">    
  2.     <canvas id="canvas"></canvas>    
  3.   </div>   
Step 10
 
Now, open app-routing.module.ts file and add the following lines to create routing.
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { BarchartComponent } from "./barchart/barchart.component";  
  4. import { LinechartComponent } from "./linechart/linechart.component";  
  5. import { PiechartComponent } from "./piechart/piechart.component";  
  6. import { DoughnutComponent } from "./doughnut/doughnut.component";  
  7. const routes: Routes = [  
  8.   {  
  9.     path: 'LineChart', component: LinechartComponent  
  10.   
  11.   },  
  12.   {  
  13.     path: 'BarChart', component: BarchartComponent  
  14.   },  
  15.   {  
  16.     path: 'PieChart', component: PiechartComponent  
  17.   },  
  18.   {  
  19.     path: 'DoughnutChart', component: DoughnutComponent  
  20.   },  
  21.   
    {
    path:'Polarchart',component:PolarareaComponent
    }
  22.   
  23. ];  
  24.   
  25. @NgModule({  
  26.   imports: [RouterModule.forRoot(routes)],  
  27.   exports: [RouterModule]  
  28. })  
  29. export class AppRoutingModule { }  
Step 11
 
Open app.component.html file and add the following HTML.
  1. <div>  
  2.   <div class="row">  
  3.     <div class="col-sm-12 btn btn-primary">  
  4.       Batsman Performance Analysis  
  5.     </div>  
  6.   </div>  
  7.   <div class="row" style="margin-top:10px;margin-bottom: 10px;">  
  8.     <div class="col-sm-2">  
  9.       <button class="btn btn-success" routerLink="/LineChart">Line Chart</button>  
  10.     </div>  
  11.     <div class="col-sm-2">  
  12.       <button class="btn btn-success" routerLink="/BarChart">Bar Chart</button>  
  13.     </div>  
  14.     <div class="col-sm-2">  
  15.       <button class="btn btn-success" routerLink="/PieChart">Pie Chart</button>  
  16.     </div>  
  17.     <div class="col-sm-2">  
  18.       <button class="btn btn-success" routerLink="/DoughnutChart">Doughnut Chart</button>  
  19.     </div>  
  20.     <div class="col-sm-2">  
  21.       <button class="btn btn-success" routerLink="/Polarchart">Polar Area</button>  
  22.     </div>  
  23.     <div class="col-sm-2">  
  24.     </div>  
  25.   
  26.   </div>  
  27. </div>  
  28. <hr style="background-color:black" />  
  29.   
  30. <router-outlet></router-outlet>  
Step 12
 
Now, open app.module.ts file and add the following code.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';  
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { AppComponent } from './app.component';  
  6. import { LinechartComponent } from './linechart/linechart.component';  
  7. import { BarchartComponent } from './barchart/barchart.component';  
  8. import { PiechartComponent } from './piechart/piechart.component';  
  9. import { DoughnutComponent } from './doughnut/doughnut.component';  
  10. import { PolarareaComponent } from './polararea/polararea.component';  
  11. @NgModule({  
  12.   declarations: [  
  13.     AppComponent,  
  14.     LinechartComponent,  
  15.     BarchartComponent,  
  16.     PiechartComponent,  
  17.     DoughnutComponent,  
  18.     PolarareaComponent,  
  19.   ],  
  20.   imports: [  
  21.     BrowserModule,  
  22.     AppRoutingModule,  
  23.     AppRoutingModule,  
  24.     HttpClientModule  
  25.   ],  
  26.   providers: [],  
  27.   bootstrap: [AppComponent]  
  28. })  
  29. export class AppModule { }  
Step 13
 
Now, run the project, click on the buttons and check the result.
 
Line Chart
 
Create Charts In Angular 7 Application Using Chart.js 

Bar Chart
 
Create Charts In Angular 7 Application Using Chart.js 

Pie Chart
 
Create Charts In Angular 7 Application Using Chart.js
 
Doughnut Chart
 
Create Charts In Angular 7 Application Using Chart.js
 
PolarArea Chart
 
Create Charts In Angular 7 Application Using Chart.js
 

Summary

 
In this article, we learned about Chart.js and how we add chart.js in an Angular application to create Charts. In this article, we discussed the line chart, bar chart, pie chart, doughnut chart, and polar area chart.