Creating Dynamic Graphs using Angular and Chart.js with Array Values

I have implemented ChartJS-2 to visualize a graph displaying an array of user activities, but it appears distorted:

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,
    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>

Instead of the expected graph, all barChartLabels are stacked on top of each other and only one barChartData is displayed. I attempted to debug my code without success.

Answer №1

The root of the problem lies in this particular line

this.barChartLabels = [startDateArry];

At this point, you are essentially inserting the array startDateArry as the first item within the array this.barChartLabels; instead, you should simply 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 where the issue lies!', this.barChartLabels);

    /* SOLUTION */
    this.barChartLabels = startDateArry;
    console.log('this is how to fix it!', this.barChartLabels);
  }
}

You can observe the distinction between these two statements in the linked functioning stackblitz as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring TypeScript Compiler Options for ensuring code compliance beyond the confines of strict mode

Our goal is to set up TypeScript Compiler (TSC) with a command line option that can identify errors when developers declare class fields using implicit type expressions instead of explicit ones as illustrated below. class Appliance { //Desired coding ...

Dealing with time zone offsets in Angular 2 Date Pipe even without a specific offset

I am currently facing an issue with converting a date string to display it on the UI using the date pipe in Angular. Below is an example of the date value: "2017-02-07T21:23:19.163" Here is the template code I am working with: <div class="input-gro ...

How come TypeScript does not detect when a constant is used prior to being assigned?

There's an interesting scenario I came across where TypeScript (3.5.1) seems to approve of the code, but it throws an error as soon as it is executed. It appears that the root cause lies in the fact that value is being declared without being initiali ...

Angular2: Leveraging click events to manage CSS classes on elements

I am currently developing a web app using Angular 2. I'm facing an issue where the active element should receive an extra CSS class when clicked, but adding the ":active" CSS attribute with a custom class doesn't work as expected. The ":focus" pr ...

Error: The function setIsEnabled does not exist

Currently, I am in the process of merging two separate next.js projects to create a website that can utilize the Cardano wallet 'Nami'. The code for accessing the wallet functions correctly in its original project, but when transferred over, it p ...

Error in refreshing the deployment package of angular 4 on an Apache server

At the moment, my Angular application runs on an Apache server at the 'http://localhost' root or index page. However, when I refresh the inner page 'http://localhost/dms-data/summary-of-findings', the browser displays Page Not Found T ...

How to easily upload zip files in Angular 8

Currently, I am working on integrating zip file upload feature into my Angular 8 application. There are 3 specific requirements that need to be met: 1. Only allow uploading of zip files; display an error message for other file types 2. Restrict the file s ...

Protractor's compatibility with Headless Chrome is hindered on AWS CodeBuild, yet functions successfully when run locally

I am facing an issue with my webpage that requires Google Authentication before moving on to an angular web page. I have created some basic end-to-end tests which are working perfectly fine in Linux using Chrome Headless: The test finds the username fiel ...

Is there an issue with integrating Bootstrap with Angular 6?

npm install bootstrap Update the angular.json file: "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "styles.scss" ] Include the Bootstrap CSS directly in your src/style.css: @import '~bootstrap/dist/css/bootstrap.min.css'; A ...

I'm curious about the Next.js type that corresponds to the Redirect object

It's possible to set up redirection in Next.js by configuring it like this: module.exports = { async redirects() { return [ { source: '/about', destination: '/', permanent: true, }, ] ...

Utilize or Bring in an external JavaScript file within Ionic 2

Currently working with Ionic 2 and Typescript Angular 2 and facing an issue. I need to utilize an external JavaScript file located at . How can I import or include this in my project? ...

Bizarre Behavior of String Comparison in Typescript When Using String.toLowerCase

As someone who is naturally curious (and has no background in JS), I have decided to take the plunge into Typescript. However, I seem to have hit a roadblock. I am trying to compare two strings but want to make it easier by first converting them to lowerca ...

Encountering the following error message: "Received error: `../node_modules/electron/index.js:1:0 Module not found: Can't resolve 'fs'` while integrating next.js with electron template."

I am utilizing the electron template with next.js, and I am trying to import ipcRenderer in my pages/index.tsx file. Below is the crucial code snippet: ... import { ipcRenderer } from 'electron'; function Home() { useEffect(() => { ip ...

What are the steps for implementing angular DataTable?

Currently working with Angular 6 and trying to implement an Angular data table, but encountering the following error. Need assistance in resolving this issue and implementing the Angular data table successfully. Encountering the error shown below: ERROR ...

Tips for utilizing functions in an inline HTML translation pipe

My objective is to streamline the code by using the Angular translate pipe. Currently, I find myself using 8 curly brackets and repeating the word "translate" twice... there must be a more efficient approach. Here is my current code setup: <s ...

Uncaught ReferenceError: jQuery is undefined" - Navigating the Angular and JavaScript Realm with

There is an Angular project that I am working on, and it utilizes the AvayaClientSDK consisting of three JavaScript files. While trying to import the AvayaClientSDK JS file into my component, an error message stating "jQuery is not defined" appeared. ...

Issue with handling multiple input files in an *ngFor loop

I am facing difficulties in targeting the correct input within a *ngFor loop. When I include an image with the first input (Certificat dimmatriculation), it displays a placeholder image and a delete button to reset the input, but it appears under both divs ...

Strategies for eliminating nested subscriptions in the search for names

I need assistance with refactoring a component I created to search for GitHub users by login. The current implementation contains nested subscribe blocks, and I would like to rewrite it using rxjs operators without nesting them. You can find the live exam ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Issue with Angular2 not able to call POST method in CodeIgniter RESTful API resulting in 404 error

I am encountering an issue with my codeigniter restful API. While the GET method is working fine, I am unable to get the POST method to work from Angular2. this.api.post('quality/addeditquality', this.formdata).subscribe(data => { c ...