Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Let's build an Angular 5 Chart.js App - Tutorial

By Gary simon - Dec 11, 2017

Ready to build Awesome Angular Apps?

A Free Course, Free Tutorials and Full App Development Courses!

Great! Check your email

I've just sent you the first email to get you started.

With the abundance of beautiful JavaScript charts these days, it's a no-brainer to use them to help visualize data. 

In this tutorial, we're going to create a brand new Angular 5 app from scratch, and integrate the open source Chart.js library. Then, we're going to connect to a public API to retrieve data and ultimately display it on a chart.

Let's get started!

If you prefer watching a video..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.

As always: Prerequisites

I'm going to assume you already know this, but because we will be using Angular and the Angular CLI, we will need Node.js with the Node Package Manager (NPM). To check:

$ node -v
$ npm -v

If these go unrecognized, visit Nodejs.org and download the appropriate installer based on your OS. Install it with the default options and reload your console.

Starting the Project

Now, we're going to use the Angular CLI to generate a new Angular 5 project:

$ ng new charts && cd charts

Next, let's install the Charts.js library and save it as a dev. dependency:

$ npm install chart.js --save

We're going to generate a service file, which is standard practice whenever you're connecting to an API to retrieve data. This way, you can easily access the API from any component:

$ ng generate service weather

Let's run the serve command and visit http://localhost:4200 in your browser after this finishes running:

$ ng serve

Retrieving the API Data

We could have just hardcoded some data to work with, but since most of you will be charting data retrieved through a service, I figured I would show that process too.

Open up the /src/app/weather.service.ts file and add the following imports to the top:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';

Next, in the WeatherService class, add:

export class WeatherService {

  constructor(private _http: HttpClient) { }

  dailyForecast() {
    return this._http.get("http://samples.openweathermap.org/data/2.5/history/city?q=Warren,OH&appid=b6907d289e10d714a6e88b30761fae22")
      .map(result => result);
  }

}

We're first creating an instance of the HttpClient through dependency injection, and then we're creating a method called dailyForecast() to return data from a sample API endpoint from OpenWeathermap.org.

If you wish to connect to their real API, it will require creating a free account and connecting to an endpoint with an API key. We won't be doing this, simply because it extends too far outside of the scope of this tutorial.

Next, we have to import our WeatherService and the HttpModule.

Open /src/app/app.module.ts and add:

// Other imports removed for brevity

import { HttpClientModule } from '@angular/common/http';
import { WeatherService } from './weather.service';

@NgModule({
  ...
  imports: [
    BrowserModule,
    HttpClientModule             // Add this
  ],
  providers: [WeatherService],   // Add this
  ...
})

Next, open up the */src/app/app.component.ts file and import our WeatherService and Chart.js, then give ourselves access to it through DI in the constructor:

import { Component } from '@angular/core';
import { WeatherService } from './weather.service';
import { Chart } from 'chart.js';

//@Component code removed for brevity

export class AppComponent {

  chart = []; // This will hold our chart info

  constructor(private _weather: WeatherService) {}

  ngOnInit() {
    this._weather.dailyForecast()
      .subscribe(res => {
        console.log(res)
      })
  }
}

I also made the call here to our weather service dailyForecast() method to console.log the data.

Check out your browser and open up the console and you should see the returned data.

Structuring the Data

Remove the console.log(res) line and add the following:

let temp_max = res['list'].map(res => res.main.temp_max);
let temp_min = res['list'].map(res => res.main.temp_min);
let alldates = res['list'].map(res => res.dt)

let weatherDates = []
alldates.forEach((res) => {
    let jsdate = new Date(res * 1000)
    weatherDates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
})

In order for our chart to use the data correctly, we have to format it. So, assuming we want the temp_max, temp_min, and their associated dates (dt), then we have to define variables for each.

The .map operator allows us to directly access properties within the returned response.

The .forEach allows us to iterate through the unix timestamps and convert each one to a readable date through .toLocaleTimeString 

Chart.js Code

Just beneath the alldates.forEach() code, add the following:

        this.chart = new Chart('canvas', {
          type: 'line',
          data: {
            labels: weatherDates,
            datasets: [
              { 
                data: temp_max,
                borderColor: "#3cba9f",
                fill: false
              },
              { 
                data: temp_min,
                borderColor: "#ffcc00",
                fill: false
              },
            ]
          },
          options: {
            legend: {
              display: false
            },
            scales: {
              xAxes: [{
                display: true
              }],
              yAxes: [{
                display: true
              }],
            }
          }
        });

There are a variety of charts that Chart.js offers, along with many options and properties for configuration. I won't go through all of them here, so you can check out their documentation to learn more.

We're defining a line chart, and you can see for the labels property we're specifying the weatherDates, and then we have 2 datasets, each showing the temp_min and temp_max arrays.

Adjust the Template

Open up /src/app/app.component.html and remove everything there, and replace it with:

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

Give it a go!

You should now check out your browser and with any luck, your result should look like this:

Hopefully you learned a lot here!

As you can see, the charts are great looking and also very flexible.


Share this post




Say something about this awesome post!