Angular 12 Bar Chart Using ng2-Charts

watch_later 29 May, 2021

In this article, we will learn how to create a bar chart in angular 12 using ng2-charts. Here, I'll explain how to create an angular 12 project in visual studio 2019 and install the npm package ng2-charts using the package manager console. I will also explain the way to upgrade your old version of angular with the latest version of angular so you can keep your project or angular application up to date.

In my previous articles, I explained AngularJS Pie Chart Using Highcharts Library With Example and How to Plotly Charts using JavaScript with Examples that you may like to read.


Angular 12 Bar Chart


I noticed many developers, programmers, as well as students, especially those who are beginners, many times, get difficulties while they are work with charts in angular, either in version update, data binding, npm package installation and etc. 

A few days ago I got an email from one of my readers, she was a student and she needed help to create a bar chart in her angular project, as she was getting some issues in the npm package installation as well as in the data binding. I have created a demo angular application to help her, so in this article, I would like to share that demo application with all the developers as well as the student's community, so needful developers of students can get help from this article.

Requirement

  1. Create a new angular 12 application.
  2. Install ng2-charts npm package using the package manager console.
  3. Create bar chart using ng2-charts

Implementation

Let's we start with an example of students, we will create a bar chart for students for subject wise marks/score.

So, first, we have to install angular CLI into our system, if you already installed angular CLI into your system then you can skip this step.

To, install angular CLI open the package manager console from the visual studio or open the command prompt and type the below command, and press enter.
npm install - g @angular/CLI
NOTE: If you facing any issue related to npm then you have to download and install the active LTS, or maintenance the LTS version of Node.js.  
If you are running an older version of angular and wants to update your angular application with the latest version of angular you can use the following command:
ng update @angular/core @angular/cli --force
If, you are using an angular material theme, and wants to update the latest version of angular material you can use the following command:
ng update @angular/material --force
Now, we have to create a new angular project.

Create New Angular Project

Create a new angular project open package manager console from visual studio, write the following command, and hit enter.
ng new Codingvila
Here, Codingvila is the name of our Angular project.

To verify the installed version of angular or you can use the following command.
ng version
So, now we have to Install ng2-charts npm Package in our angular project.

Install ng2-charts npm Package in Angular Project


To, install the ng2-charts npm package, you can use the following command:
npm install ng2 - charts@2.2.3 --save
npm install chart.js@2.9.3 --save
You can also check the package.json file in the angular project to verify the installed packeges.

package.json

{
  "name""codingvila",
  "version""0.0.0",
  "scripts": {
    "ng""ng",
    "start""ng serve",
    "build""ng build",
    "watch""ng build --watch --configuration development",
    "test""ng test"
  },
  "private"true,
  "dependencies": {
    "@angular/animations""~12.0.2",
    "@angular/common""~12.0.2",
    "@angular/compiler""~12.0.2",
    "@angular/core""~12.0.2",
    "@angular/forms""~12.0.2",
    "@angular/platform-browser""~12.0.2",
    "@angular/platform-browser-dynamic""~12.0.2",
    "@angular/router""~12.0.2",
    "chart.js""^2.9.3",
    "ng2-charts""^2.2.3",
    "rxjs""~6.6.0",
    "tslib""^2.1.0",
    "zone.js""~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular""~12.0.2",
    "@angular/cli""~12.0.2",
    "@angular/compiler-cli""~12.0.2",
    "@types/jasmine""~3.6.0",
    "@types/node""^12.11.1",
    "jasmine-core""~3.7.0",
    "karma""~6.3.0",
    "karma-chrome-launcher""~3.1.0",
    "karma-coverage""~2.0.3",
    "karma-jasmine""~4.0.0",
    "karma-jasmine-html-reporter""^1.5.0",
    "typescript""~4.2.3"
  }
}

Explanation


As you can see in the package.json file, look at the dependencies that indicate our npm package chart.js, as well as ng2-charts, has been installed successfully.

Now, we have to import the chart module, for that, you have to open the app.module.ts file witch is located in the following directory Codingvila >> src > > app >> app.module.ts.

Now, write the following code into the app.module.ts file.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ChartsModule } from 'ng2-charts';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ChartsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Explanation



As you can see in the code of the app.module.ts file as written above, here we have imported a ChartsModule from the ng2-charts as well as imported a FormsModule from the @angular/forms.

In the same way, we have to update our app.component.ts file, which is located in the following directory Codingvila > src > app > app.component.ts.

Write the following code into app.component.ts

app.component.ts

import { Component } from '@angular/core';
import { ChartDataSets } from 'chart.js';
import { ChartOptions, ChartType } from 'chart.js';
import { Label } from 'ng2-charts';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Codingvila';
  public chart_Options: ChartOptions = {
    responsive: true,
  };
  public chart_Labels: Label[] = ['Nikunj Satasiya''Hiren Dobariya''Vivek Ghadiya''Shreya Patel''Pratik Pansuriya''Keval Patel'];
  public chart_Type: ChartType = 'bar';
  public chart_Legend = true;
  public chart_Plugins = [];

  public chart_Data: ChartDataSets[] = [
    {
      data: [65, 67, 70, 75, 80, 90],
      label: 'Mathematics'
    },
    {
      data: [50, 48, 47, 49, 44, 40],
      label: 'Science'
    },
    {
      data: [43, 30, 28, 25, 22, 20],
      label: 'English'
    },
    {
      data: [40, 32, 40, 30, 28, 22],
      label: 'Drawing'
    },
    {
      data: [70, 38, 28, 27, 23, 19],
      label: 'Chemistry'
    },
  ];

  constructor() { }

  ngOnInit() {
  }
}

Explanation


As you can see in the code above, here we have imported the ChartDataSets, ChartOptions, and ChartType from the installed npm package chart.js and label for the bar chart imported from ng2-charts. Here, we have taken the name of the student as a label of the bar chart and assign JSON data as a dataset which contains subject wise marks/score of particular student. In this example, we have created a static JSON dataset for demonstration, you can retrieve the JSON dataset from your service or from your web API based on your requirement. 

Now, we will design our HTML page, to do that you should open the app.component.html file witch is located in the following directory Codingvila > src > app > app.component.html.

app.component.html

<style>
  :host {
    font-family-apple-systemBlinkMacSystemFont"Segoe UI"RobotoHelveticaArialsans-serif"Apple Color Emoji""Segoe UI Emoji""Segoe UI Symbol";
    font-size14px;
    color#333;
    box-sizingborder-box;
    -webkit-font-smoothingantialiased;
    -moz-osx-font-smoothinggrayscale;
  }

  .toolbar {
    positionabsolute;
    top0;
    left0;
    right0;
    height60px;
    displayflex;
    align-itemscenter;
    background-color#223c88;
    colorwhite;
    font-weight600;
  }
  .logo{padding-left:20px;
        font-sizelarge;
  }
 
  .chart {
    width800px;
    height1100px;
    displayblock;
    padding-top:100px;
    padding-left:30px;
  }

  @media screen and (max-width575px) {
    svg#rocket-smoke {
      displaynone;
      visibilityhidden;
    }
  }
</style>

<div class="toolbar" role="banner">
  <span class="logo">Codingvila | Angular 12</span>
  <div class="spacer"></div>
</div>

<div class="chart">
  <canvas baseChart
          [datasets]="chart_Data"
          [labels]="chart_Labels"
          [options]="chart_Options"
          [plugins]="chart_Plugins"
          [legend]="chart_Legend"
          [chartType]="chart_Type">
  </canvas>
</div>

Explanation


As you can see in the HTML code above, first we have written a CSS class to give the proper user interface to our angular application, Then we have created the bar chart using the canvas tag, and assigned the appropriate properties, as those properties where we have assigned a value in the app.component.ts file.

Now, we have to build and run our angular project, to build the project of angular you have to write the following command in the package manager console.

Build an Angular Project

ng build

Run Angular Project

ng serve -o
When you press enter your angular project will run on URL: http://localhost:4200/

Output


Angular 12 Bar Chart using ng2-charts

Summary


In this article, we learned about the bar chart in angular 12 application using ng2-charts as well as also learned how to update the latest version of angular and etc.

You can download the source code from here if you want to do practice to create a bar chart in the angular 12 application using ng2-charts.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon