AppDividend
Latest Code Tutorials

Angular Charts Example Tutorial

390

Get real time updates directly on you device, subscribe now.

Angular Charts Example Tutorial is today’s leading topic. We will use the chart.js library to construct the charts. I am using Angular 6 for this example. For that, you already have installed the Node.js in your machine because we use Angular CLI to install Angular. So node and npm is the must requirement for this example. So If you have not installed previously, then you can go to this link.

Angular Charts Example Tutorial

Okay, first install the Angular.

#1: Install Angular using Angular CLI

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

sudo npm install -g @angular/cli

If you are Linux or Mac user then and then write sudo. In windows, open the CMD in admin mode and write the above command without sudo.

Now, create a new project using the following command.

ng new charts

 

Angular Charts Example Tutorial

Go into the project folder.

cd charts

Open the project inside Editor using the following command.

code .

Now, install the chartjs library using the following command.

npm install chart.js --save

Also, you need to install rxjs-compat package. Some third-party packages are incompatible with Angular 6 that is why we need to add the following package to bridge the gap.

npm install rxjs-compat.js --save

#2: 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 example. So let us install the package using Yarn package manager. If you have previously installed, then you do not need to install it again.

npm install -g json-server

Now, create one file called data.json inside the root of the project. We will see the chart of the Apple’s stock price from Jan to Sept.

{
  "results": [
  {
      "month": "Jan",
      "price": "180"
  },
  {
    "month": "Feb",
    "price": "200"
  },
  {
    "month": "March",
    "price": "210"
  },
  {
    "month": "April",
    "price": "190"
  },
  {
    "month": "May",
    "price": "240"
  },
  {
    "month": "June",
    "price": "230"
  },
  {
    "month": "July",
    "price": "260"
  },
  {
    "month": "Aug",
    "price": "210"
  },
  {
    "month": "Sept",
    "price": "300"
  }]
}

Now, start the JSON Server using the following command.

json-server --watch data.json --port 4000

 

Angular 6 Charts Tutorial Example

#3: Add HttpClientModule in 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) {}
}

#4: Create a data.ts file

Inside the src >> app folder, create one file called Data.ts and add the following code in it.

// Data.ts

export interface Data {
  month: String;
  price: Number;
}

So we are expecting month and price data from an API.

#5: Send a request and display chart.

Related Posts
1 of 14

Now, we need to import the Chart library inside an app.component.ts file and then use Chart api to display the data. The dataset for this example comes from the backend json server.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
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';
  month = [];
  price = [];
  chart = [];
  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    this.httpClient.get(this.url).subscribe((res: Data[]) => {
      res.forEach(y => {
        this.month.push(y.month);
        this.price.push(y.price);
      });
      this.chart = new Chart('canvas', {
        type: 'line',
        data: {
          labels: this.month,
          datasets: [
            {
              data: this.price,
              borderColor: '#3cba9f',
              fill: false
            }
          ]
        },
        options: {
          legend: {
            display: false
          },
          scales: {
            xAxes: [{
              display: true
            }],
            yAxes: [{
              display: true
            }],
          }
        }
      });
    });
  }
}

So, here first we have sent the request to a server and we get the response. Now, we have stored the response in two different arrays because further in the chart, we need to use that arrays.

One array called a month is for the label and another is called price for the dataset.

We have constructed the line chart for this example, but you can create more. Follow the official docs.

#6: Add chart inside the app.component.html file.

The final step would be to add the chart inside the app.component.html file.

<div *ngIf="chart">
  <canvas id="canvas">{{ chart }}</canvas>
</div>

Save the file. Also, check your app.module.ts file with mine.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

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

Go to the terminal and type the following command to start the Angular development server.

ng serve --open

It will open the browser and you can see the Chart like below image.

 

Charts in Angular 6

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

2 Comments
  1. Maria says

    I did not get the program/chart running. It’s giving an errors like:
    GET http://localhost:4000/results 404 (Not Found)
    HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: “Not Found”, url: “http://localhost:4000/results”, ok: false, …}
    error: {}
    headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
    message: “Http failure response for http://localhost:4000/results: 404 Not Found”
    name: “HttpErrorResponse”
    ok: false
    status: 404
    statusText: “Not Found”
    url: “http://localhost:4000/results”
    __proto__: HttpResponseBase

  2. Wiliam Kahler says

    Great demo. Thank you, I had it running in minutes.

    It is pretty self explanatory, but It might be worth pointing out the following:
    – “npm install rxjs-compat.js –save” failed for me, but I already have the rsjx basic library, and it seems to work without the rxjs-compat part of it…
    – the data.json file from step #2 should be at the very root of the project, at the same level as package.json
    – when you run the test, you need to run two instances: The server (port 4000), and the client app (port 4200).

Leave A Reply

Your email address will not be published.

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