Thursday, 13 September, 2018 UTC


Summary

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
 
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
 
#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.
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.
 
Finally, Angular Charts Example Tutorial is over. Thanks for taking this demo.
The post Angular Charts Example Tutorial appeared first on AppDividend.