Enhancing labels and data in Angular 8 with ng2 charts

I am currently working on an Angular project that involves a chart created with ng2-charts. The data for this chart is entered by the user through a select box for labels and an input field for the data. While I have been able to update the chart with new data entries, any changes made do not actually update the existing values; instead, they simply add them as new ones. You can see examples of this behavior in the screenshots below:

Despite searching various sources online, I have yet to find a solution that addresses my issue. It seems likely that the problem lies in targeting the specific area of the array, but the correct code eludes me. Below is my current code, which allows for adding data but not updating it:

I've included the relevant HTML and TypeScript (TS) files for reference: HTML:


        <div class="deposit-container">
          // Code for chart container and user-input fields
        </div>

TS file excerpt:


      // Deposits array containing preset values
      deposits: Deposit[] = [
        { value: 'Builders Gift', viewValue: 'Builders Gift' },
        // Additional preset values
      ];

      // Data arrays for chart creation
      public doughnutChartLabels: any [] = [];
      public doughnutChartData: any [] = [];

      // Doughnut chart configuration options
      public doughnutChartOptions = {
        legend: {
          display: false,
        }
      };

      getLabel(depositParent) {
        // Function for retrieving and pushing selected label data
      }

      getData(depositParent) {
        // Function for retrieving and pushing input data
      }

The inability to update or overwrite existing data has led me to experiment with different approaches, such as modifying array indexes directly or utilizing datasets. Despite these attempts, none have proven successful so far.

If anyone has encountered a similar scenario or has suggestions on how to efficiently edit data within an array dynamically, your insights would be greatly appreciated!

Answer №1

When attempting to apply translations to graph labels, I faced a similar issue. I recall reading on stackoverflow that it's necessary to change the reference of the array used in the graph.

For instance, you could try:

 getLabel(depositParent) {
    let target = this.depositSourceValue[depositParent];
    this.doughnutChartLabels = [...this.doughnutChartLabels, depositParent];
    // this.chart.chart.update();
  }

  getData(depositParent) {
    let data = this.depositSourceAmount[depositParent];
    this.doughnutChartData = [...this.doughnutChartData, depositParent];
    // this.chart.chart.update();
  }

I recommend using a service with an Observable that this component can subscribe to for receiving notifications and triggering the code to update the graph.

Hopefully, this solution proves helpful.

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 functionality of Angular Flex Layout's Static API for vertical or horizontal space-around with no alignment appears to be malfunctioning

Can someone explain why the spacing around alignment isn't functioning here? I'm getting the same result for space-between. What could I be overlooking? ...

Deploying Angular distribution files to a Tomcat server causes the routes to be interpreted as directories

I encountered challenges with CORS when trying to communicate between Angular serve port 4200 and my Tomcat 8080 port. To resolve this, I decided to move my Angular project into my Java WebContent directory and serve the dist folder directly. This fixed ...

Exploring the <> syntax in Angular2 with Typescript

I am brand new to Angular2 and struggling to grasp the < > syntax : For instance, in example 1 (found at https://angular.io/docs/ts/latest/guide/dependency-injection.html): let mockService = <HeroService> {getHeroes: () => expectedHeroes } ...

Guide on launching a bootstrap modal using ngIf

Hello everyone, I appreciate your patience as I am new to this! Currently, I am attempting to activate a Bootstrap modal using an ngIf condition. Specifically, the goal is for the modal to open when there is existing artwork present and allow for the addit ...

Align the input of the child component with the grandparent. Numerous indications point to the need for synchronization

I have a structure of components outlined below: main component sub component intermediate component with the <input> component The main component contains a changeset object that is populated from the ngrx store. I am looking for an Angular ...

Obtain the selected value of 'id' from an autocompletion feature in Angular Material

How can I configure mat-autocomplete to retrieve the ID of the selected option? <mat-form-field> <input type="text" matInput [formControl]="autocompleteControl" [matAutocomplete]="auto"> ...

Utilizing a variety of Angular modules within Asp.Net Core

What is the optimal way to utilize multiple Angular 4 modules within the context of Asp.Net Core MVC? I am working on an application with various sections, each managed by a controller and view. Within these sections, I aim to incorporate sub-sections usi ...

Defining optional parameters in TypeScript

Currently, I am working on implementing strong typing for a flux framework (specifically Vuex). Here is my current code: const actions = { first(context: Context, payload: string) { return doSomething(context, payload); }, second(context: Context) { r ...

I am perplexed by the CommonJS pattern, TypeScript modules, and how to effectively utilize ES6

Hey there, everyone! I'm curious if someone could provide me with a straightforward comparison of the development flow when working with CommonJS, Typescript, and ES6 in relation to the module import system (such as require(), import "xx", export), c ...

What is the best way to integrate a service-defined class into a component in Angular?

Is there a way to utilize a class that is defined in a service within a component? The Service.ts file includes a class that I would like to use in my component. Despite injecting the service into the component, I am encountering difficulties in accessing ...

Sending a parameter through a route to a child component as an input in Angular 2

My parent component receives an id value from a route parameter and I need to pass this value to a child component using the Input() decorator. The issue I'm facing is that I can't seem to get the route param value to be passed to the child compo ...

Creating a build task in Visual Studio Code with universal TypeScript compiler settings

Our project has the following structure: +-- views +-- viewXXX +-- ts ¦ +-- controller.ts ¦ +-- helper.ts ¦ +-- ... (*.ts) +-- viewXXX.ctrl.js // this is the desired output file +-- viewXXX.c ...

MatTooltipClass Causes MatTooltip to Disappear Almost Instantly

Utilizing Angular Material for tooltips, my code looks like this: <button mat-raised-button matTooltip="Line one&#13;line two..." matTooltipClass="tooltip" (click)="onOne()" > One </button> <button ...

Creating TypeScript declaration file for exporting JavaScript function

I'm a beginner with TypeScript and I want to learn how to create a declaration file for a custom JavaScript function. I attempted to do this, however, I encountered an error stating "Could not find a declaration file for module './main'." Ad ...

Effective method of delegating a section of a reactive form to a child component in Angular 5

Here is a form declaration for reference: this.form = this.fb.group({ party: this.fb.group({ name: [null, Validators.required], givenName: [null, Validators.required], surname: [null, Validators.required], ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

obtaining the status of a checkbox in ionic2

Here is the scenario: I am managing a list of users. Additionally, I have a collection of items where each item contains an array of associated users. The display of the items list is as follows: <ion-list> <ion-item *ngFor="let item of it ...

Instructions for uploading a pre-rendered file to Amazon S3 and accessing it when our webpage loads for the first time

My web application is built using Angular Universal Starter kit. I'm looking to optimize the initial page load speed by uploading the pre-rendered file to an S3 bucket. However, I am having trouble finding the correct configurations for uploading the ...

What is the method to retrieve the data type of the initial element within an array?

Within my array, there are different types of items: const x = ['y', 2, true]; I am trying to determine the type of the first element (which is a string in this case because 'y' is a string). I experimented with 3 approaches: I rec ...

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...