Search code examples
angulartypescriptchartschart.js2ng2-charts

Angular: How to show graph in chartjs with dynamics values (arry)


I'm trying to use chartJS-2 to show a graph with an array of user activities, but it's not displaying properly:

import { Component, OnInit, Input } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import * as pluginDataLabels from 'chartjs-plugin-datalabels';
import { Label } from 'ng2-charts';
import { IblinkPoint } from 'src/app/iblink-point';
import { OpenWebService } from 'src/app/blinking/open-web.service';

@Component({
  selector: 'app-graph',
  templateUrl: './graph.component.html',
  styleUrls: ['./graph.component.scss']
})
export class GraphComponent implements OnInit {
  public barChartOptions: ChartOptions = {
    responsive: true,
    // We use these empty structures as placeholders for dynamic theming.
    scales: { xAxes: [{}], yAxes: [{}] },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
      }
    }
  };
  public barChartType: ChartType = 'bar';
  public chartColors: Array<any> = [
    {
      backgroundColor: 'rgb(77, 0, 77, 1)',
      borderColor: 'rgba(77, 0, 77, 1)',
      borderWidth: 2,
    }
  ];

  public barChartData: ChartDataSets[];
  public barChartLabels: Label[];

  @Input() blinks: IblinkPoint[];
  constructor(private openWebService: OpenWebService) { }

  ngOnInit() {
    let arrBlinks = this.openWebService.getBlinkData();
    let startDateArry: any[] = [];
    let endDateArry: any[] = [];
    let blinkArry: any[] = [];
    arrBlinks.forEach(element => {
    blinkArry.push(element.blinkCounter).toString;
    startDateArry.push(element.startDate.getMinutes().toString());
   // console.log(startDateArry);
    // endDateArry.push(element.endDate.getHours());
    });
    this.barChartLabels = [startDateArry];
    this.barChartData = [{ data: blinkArry, label: 'blinks'}];
  //  console.log(this.barChartData);
  //  console.log(this.barChartLabels);
  }

}
<div style="display: block">
  <canvas baseChart
    [datasets]="barChartData"
    [labels]="barChartLabels"
    [chartType]="barChartType"
    [colors]="chartColors">
  </canvas>
</div>

I expect to see a graph, but instead it's showing all barChartLables in one place stacked on top of each other and only one barChartData. I tried debugging my code, but couldn't find any problem.


Solution

  • The issue is caused by this statement

    this.barChartLabels = [startDateArry];

    this is when you are inserting the array startDateArry as the first item of the array this.barChartLabels; instead you should just do:

    this.barChartLabels = startDateArry;

    relevant HTML:

    <div style="display: block;">
      <canvas baseChart 
        [datasets]="barChartData"
        [labels]="barChartLabels"
        [options]="barChartOptions"
        [plugins]="barChartPlugins"
        [legend]="barChartLegend"
        [chartType]="barChartType">
      </canvas>
    </div>
    

    relevant TS:

    import { Component, OnInit } from '@angular/core';
    import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
    import { Label } from 'ng2-charts';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      public barChartOptions: ChartOptions = {
        responsive: true,
        // We use these empty structures as placeholders for dynamic theming.
        scales: { xAxes: [{}], yAxes: [{}] },
        plugins: {
          datalabels: {
            anchor: 'end',
            align: 'end',
          }
        }
      };
      public barChartLabels: Label[];
      public barChartType: ChartType = 'bar';
      public barChartLegend = true;
      public barChartPlugins = [];
      public barChartData: ChartDataSets[];
    
      constructor() {
      }
    
      ngOnInit() {
        let startDateArry: any[] = [];
        let blinkArry: any[] = [];
    
        for (var i = 0; i < 7; i++) {
          blinkArry.push(Math.round(Math.random() * 100));
          startDateArry.push(Math.round(Math.random() * 100));
        }
    
        this.barChartData = [{ data: blinkArry, label: 'blinks' }];
    
        this.barChartLabels = [startDateArry];
        console.log('this is the issue!', this.barChartLabels);
    
        /* SOLUTION */
        this.barChartLabels = startDateArry;
        console.log('this is the fix!!!', this.barChartLabels);
      }
    }
    

    you can see the difference between these 2 statements in the attached working stackblitz also