Angular 6 Charts Example Tutorial From Scratch

Angular 6 Charts Example Tutorial From Scratch is the today’s leading topic. We use the Chart.js library to display the chartsWe will discuss two charts in this tutorial. First is the BarChart, uses bars to show comparisons between categories of data. Second is the PieChart, generally used to indicate percentage or proportional data.  I will use the Axios library to send an AJAX request to a JSON server and fetch the data and display in the form of charts.

Angular 6 Charts Example Tutorial.

Start this tutorial by installing Angular 6.

#1: Install Angular 6.

If you have not installed Angular CLI previously, then install it using the following command.

npm install -g @angular/cli

# or

yarn add global @angular/cli

Now, create a local project using the following command.

ng new charts

#3: Install  ng2-charts library.

First, we need to install rxjs-compat package to compatible with latest RxJS version and then install ng2-charts library. It is the main library that responsible for charts.

npm install rxjs-compat --save

Now install our main library.

npm install ng2-charts --save

#4: Create a server that serves backend data.

We need the fake data to work with that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using Yarn package manager.

yarn global add json-server

Okay, create one file called db.json inside the root folderFor the testing purpose, let us add the following data in the db.json file. Add the following code inside a db.json file.

{
    "results": [
    {
        "name": "Ruby",
        "year": "2012",
        "count": "18117"
    },
    {
        "name": "Python",
        "year": "2012",
        "count": "100"
    },
    {
        "name": "Python",
        "year": "2014",
        "count": "200"
    },
    {
        "name": "Python",
        "year": "2016",
        "count": "300"
    },
    {
        "name": "Python",
        "year": "2018",
        "count": "100"
    },
    {
        "name": "JavaScript",
        "year": "2012",
        "count": "200"
    },
    {
        "name": "PHP",
        "year": "2012",
        "count": "14460"
    },
    {
        "name": "Java",
        "year": "2012",
        "count": "8006"
    },
    {
        "name": "C++",
        "year": "2012",
        "count": "4879"
    },
    {
        "name": "C",
        "year": "2012",
        "count": "4217"
    },
    {
        "name": "C#",
        "year": "2012",
        "count": "1866"
    },
    {
        "name": "Scala",
        "year": "2012",
        "count": "1848"
    },
    {
        "name": "Objective-C",
        "year": "2012",
        "count": "1674"
    },
    {
        "name": "Shell",
        "year": "2012",
        "count": "1284"
    },
    {
        "name": "HTML",
        "year": "2012",
        "count": "1272"
    },
    {
        "name": "Perl",
        "year": "2012",
        "count": "967"
    },
    {
        "name": "CoffeeScript",
        "year": "2012",
        "count": "793"
    },
    {
        "name": "Haskell",
        "year": "2012",
        "count": "723"
    },
        {
        "name": "Erlang",
        "year": "2012",
        "count": "644"
        },
        {
        "name": "CSS",
        "year": "2012",
        "count": "622"
        },
    {
        "name": "Emacs Lisp",
        "year": "2012",
        "count": "495"
    },
    {
        "name": "Clojure",
        "year": "2012",
        "count": "430"
    },
    {
        "name": "Lua",
        "year": "2012",
        "count": "344"
    },
    {
        "name": "Go",
        "year": "2012",
        "count": "324"
    },
    {
        "name": "Groovy",
        "year": "2012",
        "count": "210"
    },
    {
        "name": "Puppet",
        "year": "2012",
        "count": "189"
    },
    {
        "name": "VimL",
        "year": "2012",
        "count": "185"
    }]
}

Now, start the JSON Server using the following command.

json-server --watch db.json --port 4000

#5: Add HttpClientModule into an app.module.ts file.

Write the following code inside an app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
    ...
    HttpClientModule
],

Okay, now we can use http module inside an app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(private httpClient: HttpClient) {}
}

#6: Import ChartsModule.

Write the following code inside the app.module.ts file.

// app.module.ts

import { ChartsModule } from 'ng2-charts';

imports: [
    ...,
    ChartsModule
  ],

#7: Send a network request and display chart.

First, we need to create a Data.ts interface inside an app folder.

// Data.ts

export interface Data {
    name: String;
    year: Number;
    count: Number;
}

Okay, now write the following code inside the app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Data } from './Data';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  title = 'app';
  data: Data[];
  url = 'http://localhost:4000/results';
  year = [];
  count = [];

  public lineChartData: Array<any> = [
    {data: this.count, label: 'Python Language'},
  ];
  public lineChartLabels: Array<any> = this.year;
  public lineChartOptions: any = {
    responsive: true
  };
  public lineChartColors: Array<any> = [
    {
      backgroundColor: 'rgba(148,159,177,0.2)',
      borderColor: 'rgba(148,159,177,1)',
      pointBackgroundColor: 'red',
      pointBorderColor: 'red',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(148,159,177,0.8)'
    }
  ];
  public lineChartLegend: Boolean = true;
  public lineChartType: String = 'line';

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    this.httpClient.get(this.url).subscribe((res: Data[]) => {
      this.data = res.filter(r => {
        return r.name === 'Python';
      });
      this.data.forEach(y => {
        this.year.push(y.year);
        this.count.push(y.count);
      });
    });
  }
}

So, here, we have included the Data.ts interface.

Also, we have sent the network request to the json server and got the data.

Then we have filter out that data because we are only concern about Python.

Also, we have created two additional arrays for count and year because we need to display the X and Y axis for the charts.

 

Angular 6 Charts Example Tutorial

Finally, Angular 6 Charts Example Tutorial is over. Thanks for taking.

Add a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.