Charts are not displaying properly in Angular 10 when using ng2-charts

My application is supposed to display charts, but for some reason, the charts are not loading.

When I check the DOM, I see the element being created with ==$0, which is confusing to me.

I am using Angular Material, but I don't think that should be affecting the visibility of the chart.

Unfortunately, I cannot see the chart at all. What could be causing this issue?

charts.component.html

  <div>
      <div>
        <div style="display: block">
          <canvas baseChart
          width="800" height="400"
            [datasets]="barChartData"
            [labels]="barChartLabels"
            [options]="barChartOptions"
            [plugins]="barChartPlugins"
            [legend]="barChartLegend"
            [chartType]="barChartType">
          </canvas>
        </div>
        <button mat-button mat-raised-button color="primary" (click)="randomize()">Update</button>
      </div>
    </div>

charts.component.ts

    import { Component, OnInit } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import * as pluginDataLabels from 'chartjs-plugin-datalabels';
import 'chartjs-plugin-datalabels'
import { Label } from 'ng2-charts';

@Component({
  selector: 'app-charts',
  templateUrl: './charts.component.html',
  styleUrls: ['./charts.component.scss']
})

export class ChartsComponent implements OnInit {
  public barChartOptions: ChartOptions = {
    responsive: false,
    // We use these empty structures as placeholders for dynamic theming.
    scales: { xAxes: [{}], yAxes: [{}] },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
      }
    }
  };
  public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  public barChartType: ChartType = 'bar';
  public barChartLegend = true;
  public barChartPlugins = [pluginDataLabels];

  public barChartData: ChartDataSets[] = [
    { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
    { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' }
  ];

  constructor() { }

  ngOnInit() {
  }

  // events
  public chartClicked({ event, active }: { event: MouseEvent, active: {}[] }): void {
    console.log(event, active);
  }

  public chartHovered({ event, active }: { event: MouseEvent, active: {}[] }): void {
    console.log(event, active);
  }

  public randomize(): void {
    // Only Change 3 values
    const data = [
      Math.round(Math.random() * 100),
      59,
      80,
      (Math.random() * 100),
      56,
      (Math.random() * 100),
      40];
    this.barChartData[0].data = data;
  }
}

Answer №1

Perhaps the issue lies in compatibility - why not give ng-chartjs a shot instead of ng2-chartjs?
ng-chart.js
Alternatively, updating the current package may also resolve the problem.

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

Retrieve the attribute of a JSON data structure

I'm encountering an issue while trying to access the property of a JSON object named date in my Angular 6 project. Even though I assigned a variable to it, it keeps showing up as undefined. This is the snippet of code causing trouble: getHistorial(d ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...

Using Angular NgUpgrade to inject an AngularJS service into an Angular service results in an error message stating: Unhandled Promise rejection: Cannot read property 'get' of undefined; Zone:

I have noticed several similar issues on this platform, but none of the solutions seem to work for me. My understanding is that because our Ng2App is bootstrapped first, it does not have a reference to $injector yet. Consequently, when I attempt to use it ...

Attempting to grasp the concept of implementing FormArray

When I execute the following code: this.formArray = new FormArray([ new FormControl(''), new FormControl(''), ]); formControlA() { return this.formArray.at(0); } formControlB() { return this.formArray.at(1); } and then use it ...

Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this: articles: Observable<Article[]>; This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach. Now, my query is about manually ...

"The ion-label in Ionic2 is cutting off some of the text and not displaying it

I'm currently facing an issue with ion-label inside ion-item. The description is not properly displaying and instead, it shows dot-dot.. ..I need the entire text to be visible. Is there any solution available? <ion-card *ngFor="let product of prod ...

Would it be frowned upon to rely on store instead of data binding for inter-component communication when accessing my data?

Within my current framework, I house the primary business logic within selectors and effects. Components are able to request data by triggering an action that queries the necessary information through selectors. Apart from instances where *ngFor is utili ...

Assign an appropriate label to this sonarqube input field

Sonarqube flagged an issue with the following line of code: <div class="dropdown-language"> <label>{{'GENERALE.LINGUA' | translate }}</label> <select #langSelect (change)="translate.use(langSe ...

Splitting Files into Separate Directories in Angular 7

Currently, I am in the process of setting up my Angular 7 application for production and reorganizing files into different directories. angular.json "architect": { "build": { "builde ...

The devastation caused by typing errors in TypeScript

I have a preference: const settings = { theme: "light", }; and feature: const Feature = ({ setting }: Props) => ( <FeatureBlock> <FeatureValue scale="large" size={20}> {setting.theme} </Styled.FeatureValue> ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Turn off Inline CSS in Angular Universal

While rendering a site on the server with Angular Universal, the resulting page looks great. However, the source code of the pages contains an excessive amount of inline CSS (more than 50% of the document > 500kb), leading to slow download times especia ...

Error message: "Unidentified variable in the code snippet from MUIv5 sample."

Achieving the Objective To implement a drawer sidebar in MUI5 that can be toggled open and closed by the user, I am exploring the documentation for the Drawer component as well as referencing an example. Encountering an Issue Upon copying the code from ...

Having trouble retrieving a value from a reference object in React Typescript?

Struggling with a login form issue in my React TypeScript project. Below is the code for the react login form: login-form.tsx import * as React from 'react'; import { Button, FormGroup, Input, Label } from 'reactstrap' ...

Optimizing Angular6 Pipe Filter Performance for Large Arrays

I have written a filter that retrieves a subset of items from a large array consisting of around 500 items. import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchFilter' }) @Inject ...

Steps to load dynamic configuration in AngularFire2

I've been attempting to initialize angularfire2 with dynamic values, but I encounter errors when using aot. let _env = { apiKey: 'key...', authDomain: dynamicValueFromConfig, databaseURL: 'url...', ...

Error message: The class heritage events_1.EventEmitter is invalid and cannot be recognized

There seems to be a problem with the [email protected] npm dependency. I am attempting to incorporate mongodb into my Vue.js + Vite + Typescript application, but it crashes and fails to load due to an error originating from mongodb. It appears that th ...

Struggling with extracting an array of objects from a JSON file and accessing individual attributes within each object?

As a newcomer to Typescript, I am eager to work with JSON and access its objects and attributes. However, I am encountering difficulties in achieving this. I have attempted using functions like 'for of' and 'for in', but unfortunately, ...

Is there a way to retrieve the resolved data within the route definition in Angular?

I am looking to execute some actions within the route definition once the lazyloaded module is loaded. The route includes a resolver called UserDataResolverService. How can I retrieve and utilize the resolved data within the route definition? { ...

Should the token be stored in the browser's sessionStorage?

What is the preferred client-side storage option provided by web browsers? ...