Angular 7 Line Charts with chart.js

Angular 7 Line Charts with chart.js

01/02/17   15 minutes read     769 Naren Allam

Create Angular Project

Create project with the name "angularchart" by using the following command.

  • ng new angularchart

  • After Project creation, to create component, open terminal and use the following command.
  • ng g c linechart (component_name )
  • Installation Of Chart.js

    Run the following command to Install chart.js

  • npm install chart.js --save
  • Chart Creation With Angular Using Chart.js

    Open linechart.component.ts file and add the required chartjs module and other required modules.

    TYPESCRIPT  Copy
                        
                          import { HttpClient } from '@angular/common/http';
    import { Chart } from 'chart.js';
                        
                      

    linechart.component.ts file

    TYPESCRIPT  Copy
                        
                          import { Component, OnInit } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Chart } from 'chart.js';
    @Component({
      selector: 'app-linechart',
      templateUrl: './linechart.component.html',
      styleUrls: ['./linechart.component.scss']
    })
    
    export class TodayhighestComponent implements OnInit {
    
    url = http://localhost:5000/all/100    
    
    constructor(private httpClient: HttpClient){}  
      // chart creation //
    
      time: any[] = [];
      humidity: any[] = [];
      pressure: any[] = [];
      temperature: any[] = [];
      chart: any = [];
    
      ngOnInit() {
      this.httpClient.get(this.url)  
          .subscribe(
            (data) => {
    
    	// fetching data from database
              var values = data["result"];
              for (var x in values) {
                this.time.push(values[x]['time'])
                this.humidity.push(values[x]['humidity'])
                this.pressure.push(values[x]['pressure'])
                this.temperature.push(values[x]['temperature'])
              }
    
              this.chart = new Chart('canvas', {
                type: 'line',                         // Define type of chart
                yAxisName: 'humidity',
                data: {
                  labels: this.time,              //Fill data in labels
                  type :timeout,          
                  datasets: [
                    {
                      data: this.humidity,   // set data that fetch from database
                      borderColor: '#006400',
                      label: 'Humidity',
                      fill: false,
                      borderWidth: [2],
    	          backgroundColor: [       //set background color of graph
                        "#3cb371",  
                        "#0000FF",  
                        "#9966FF",  
                        "#4C4CFF",  
                        "#00FFFF",  
                        "#f990a7",  
                        "#aad2ed",  
                        "#FF00FF",  
                        "Blue",  
                        "Red",  
                        "Blue"  
                      ],
                    },
                    {
                      data: this.pressure,
                      label: 'Pressure',      // for chart lables
                      borderColor: '#54117B',
                      fill: false,
                      yAxisID: 'y-axis-1',
                      borderWidth: [2]
                    },
                    {
                      data: this.temperature,
                      label: 'Temperature',
                      borderColor: '#3562AF',
                      fill: false,
                      borderWidth: [2],
                    },
                  ]},
    
                options: {
                  
                 title: {
                  display: true,
                  text: 'Pressure',
                  position:'right',
              },          
                  legend: {
                    display: true,
                  },elements: {
                    point:
                    {
                      radius: 0,
                    },
                  },
    
                  scales: {    
                    xAxes: [
                      
                      {
                        scaleLabel: {
                          display: true,
                          labelString: 'Time'
                        },
                        type: 'time',
                        time: {
                            unit: 'minute'
                        },
                        gridLines: {
                          display: false,
                        },
                      }],
                    yAxes: [
                      {
                        scaleLabel: {
                          display: true,
                          labelString: 'Temperature/Humidity'
                        },
                        gridLines: {
                          display: false
                        },
                       
                        id: 'x-axis-1',
                        position: 'left',
                      },
    
                      {
                        id: 'y-axis-1',
                        display: true,
                        position: 'right',
    
                      }],
                  }
                }
    
              });
            });
      }
      }
                        
                      

    Now, open linechart.component.html file and add the following HTML.

    MARKUP  Copy
                        
                          <div class="chart-container" style="position: relative; height:400px; width:700px">    
      <canvas id="canvas">{{ chart }}</canvas>    
    </div> 
    
    
                        
                      

    Save all files and run the following command

  • ng serve
  • Conclusion:

    Here’s a quick breakdown of the different input options

  • chartType:     This sets the base type of the chart. The value can be pie, doughnut, bar, line, polarArea & radar.
  • legend:   A boolean for whether or not a legend should be displayed above the chart.
  • datasets:   This should be an array of objects that contain a data array and a label for each data set.
  • data:   If your chart is simple and has only one data set, you can use data instead of datasets and pass-in an array of      data points.
  • labels: An array of labels for the X-axis.

  • An object that contains options for the chart. You can refer to the official Chart.js documentation for details on the available options.


    2 Comments
    kasi

        Hi, Very Very Informative Thank you


    kasi

        Hi, Very Very Informative Thank you