ng2-charts does not display the updated labels, it only shows the data

I am currently working on an Angular application using the ng2-charts package. In one of my components, I have a pie chart displaying data retrieved from the server. Here is the code snippet for that component:

export class PieChartComponent implements OnInit {
  data: Array<number> = [];
  labels: Array<string> = ['', '', '', ''];
  private line: string;
  private department: string;

  constructor(public dataService: LineService, private route: ActivatedRoute) {
    this.route.params.forEach((params: Params) => {
      this.department = params['dep'];
      this.line = params['id'];
    });
  }

  ngOnInit() {
    this.dataService.getLineTAL(this.department, this.line).forEach(result => {
      this.data = result.map(val => val.val);
      this.labels = result.map(val => val.tag);
    });
  }    
}

Here is the HTML corresponding to the component:

<div style="display: block">
  <canvas baseChart [data]="data" [labels]="labels" [chartType]="'pie'" (chartClick)="chartClicked($event)" width="1" height="1"></canvas>
</div>

Upon debugging the application, I noticed that although the this.labels array is correctly updated with the expected values for the chart data labels, the chart itself fails to display these values when hovered over. Instead, it shows empty tooltips.

Another issue I encountered is that all default colors in the chart have inexplicably turned grey. This happened after moving this functionality into its own component. Any insights on what might be causing this?

In an attempt to resolve the issues, I tried calling this.chart.ngOnChanges({}); where chart is defined as

@ViewChild(BaseChartDirective) chart: BaseChartDirective;
before making the service call. I also experimented with
this.labels = this.labels.slice();
at the end of the result mapping process to trigger a refresh, but unfortunately, neither solution proved effective.

Update:

Despite confirming that the ngAfterViewInit event populates the chart object with accurate data and label properties, the chart continues to exhibit incorrect behavior. It still does not render as intended.

Answer №1

One issue arises with ng2-chart when attempting to simultaneously update both the labels and data properties. A simple solution is to directly set the data and then use a 0 timeout to update the labels:

ngOnInit() {
    this.dataService.getLineTAL(this.department, this.line).forEach(result => {
      this.data = result.map(val => val.val);
      setTimeout( () => {this.labels = result.map(val => val.tag)};
    });
  } 

By implementing this approach, you should be able to resolve the problem efficiently.

Answer №2

I encountered a similar issue and was able to resolve it by implementing a loaded flag.

Here is how you can structure your HTML code:

<canvas *ngIf="loaded" baseChart [data]="data" [labels]="labels" [chartType]="'pie'" (chartClick)="chartClicked($event)" width="1" height="1"></canvas>

Additionally, ensure your component.ts file includes the following:

export class PieChartComponent implements OnInit {
  data: Array < number > = [];
  labels: Array < string > = ['', '', '', ''];
  private line: string;
  private department: string;
  loaded = false;

  constructor(public dataService: LineService, private route: ActivatedRoute) {
    this.route.params.forEach((params: Params) => {
      this.department = params['dep'];
      this.line = params['id'];
    });
  }

  ngOnInit() {
    this.dataService.getLineTAL(this.department, this.line).forEach(result => {
      this.data = result.map(val => val.val);
      this.labels = result.map(val => val.tag);
    });
  }
  this.loaded = true;
}

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

The Angular 2+ page fails to load properly on Internet Explorer or SharePoint

I created an Angular 5 solution that functions well in both Chrome and Firefox within SharePoint 2013. However, I have run into issues when using IE11. The index.html file was inserted into the SharePoint page using a Content Editor web part. Even after di ...

Retrieving JSON data in Angular 2

There are limited options available on SO, but it seems they are no longer viable. Angular 2 is constantly evolving... I am attempting to retrieve data from a JSON file in my project. The JSON file is named items.json. I am pondering if I can achieve th ...

Keep going in the for await loop in NodeJS

My code snippet looks like this: for await (const ele of offCycles) { if ((await MlQueueModel.find({ uuid: ele.uuid })).length !== 0) { continue; } <do something> } I'm curious if it's possible to use a continue st ...

Using a click event to target the next div and apply a CSS class using Typescript

I am trying to create a Typescript function that will locate the next div and apply a CSS class to it. Here is what I have attempted: <ul> <li><a href="#" onclick="toggle()">Item 1</a></li> <div class="content hide ...

Tips for sending a parent property as a reference rather than a value to a child component using an @Input decorator

When a parent component passes a property to a child component using the @Input decorator in Angular 2, it is passed by value and not by reference. If there is a need to change the parent's property within the child component, the new value must be em ...

Requesting an API Delay with GET Method

Hey there, I've created a code that captures the user's CPF and sends it to the server for validation. If the CPF is valid, it will display the user's name in the console. If it's invalid, it will print "Not Found". Check out the code b ...

Creating custom web components with routing in Angular 6

Is it possible to create an Angular WebComponent or Custom Element with routing modules in Angular 6? I have successfully created a web component with atomic components and now I want to expand it to have multiple screens using the routing module. Here ar ...

What is the necessity of ngrx/store when services and localStorages are available for use?

When it comes to Angular, we rely on ngrx/store to manage the state. However, I question whether all tasks can be effectively handled using services alone. What benefits does implementing the ngrx/store package offer? Your insights would be greatly appre ...

Creating an NPM package that utilizes global types without altering the project it is integrated with

The Dilemma: When working on a project that involves reusing multiple types across various files, utilizing types defined in a script file can be advantageous. These global types are accessible throughout the entire project without the need for importing, ...

Exploring Angular: Enhancing Routing through GET Requests

I've been working on a cutting-edge application that combines an Angular 2 frontend with a powerful Java backend. An exciting feature of this application is a dynamic form, consisting of various search criteria. Upon submission, I execute an http get ...

What could be the reason why the keypress event doesn't seem to be functioning properly on

Currently, I am utilizing Angular and the Ionic framework. Here is a snippet of the HTML code that I have written: <div><ion-input type="text" id="phoneNumber" [(ngModel)]="phoneNumber" (keypress)="phoneNumericCh ...

A TypeScript Class that Refers to Itself

I need help with representing a JSON object in an Angular2 typescript class. The JSON object contains an array of objects of its own type. Here is what the JSON object looks like: { "data": { "id": 5, "type": "taxons", "attributes": { ...

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...

Steps for generating a signal that postpones the primary signal and promptly resets

I am looking to create a signal that will automatically switch to an underlying signal or memo after a specific delay, and reset immediately if the primary signal is cleared. The code snippet below illustrates my desired functionality. import { render } fr ...

Why is it important to understand the role of ngOnInit() in Angular?

Is it possible to execute all the identical functions it does in the constructor? ...

Angular2's counterpart to the angular.version property in AngularJS

If you open the browser's developer console (you can press F12), and type in "angular.version", it will display the version of AngularJS APP that is currently loaded on the page. Is there a similar command for finding out the version of Angular2? ...

Primeng color selection panel not displaying fully

I am having an issue with the primeng colorpicker. When I click on the colorpicker, the panel that comes up is cut off like this: https://i.sstatic.net/t7Z5V.png How can I make the panel pop out instead of being cut off? I tried using appendTo=body but i ...

Leverage React components for efficient code reuse and export modules for

I have Project X, which was built using the command "yarn build" and it generated a main.js file. I am trying to use this main.js file as a dependency for another React project Y. Unfortunately, following the steps from React components and module exports ...

Is there a way to access the value of a variable from a .ts file within a .scss file?

Utilizing a css-only pie chart, I am looking to incorporate the value of this.performance in my scss to determine the percentage. How can I manipulate my scss file from .ts file? Below is a snippet of my css code in scss: $configs: ( chart-one: ( sv ...

trouble seeing images with an array input and ngFor in Angular

I am encountering issues while attempting to exhibit an array of images by their source link using ngFor. It seems like there are errors hindering the functionality! Below is the image HTML code located within my card component: <div class="Session-Pa ...