What is the best way to asynchronously refresh Angular 2 (or 4) PrimeNg Charts?

Issue: How can PrimeNg Charts be updated asynchronously?

Situation: I have a dropdown menu that should trigger a chart refresh based on the user's selection.

I believed I had the solution figured out, understanding Angular change detection and realizing I needed to reassign an object for changes to be recognized. However, after exploring various charts and attempting different solutions, I discovered that the problem was more complex than anticipated.

While looking into ng2-charts, which utilizes directives from charts.js, I found workaround solutions in Angular. Here is an example snippet from their code:

/**
* (My assumption): For Angular to detect dataset changes,
* it needs to directly modify the dataset variable.
* One possible method is to clone the data, make changes, and then
* assign it back;
**/

Despite their approach of stringifying and reparsing data to create a cloned copy, which worked for them, I attempted the same with PrimeNg without success.

In other instances, methods like .slice() on the chart data or direct access to CHART_DIRECTIVES followed by .update() were used. Some waited to draw the chart until data was loaded asynchronously, but this only occurred once and did not satisfy my requirements. Why should I practice Test Driven Development and how should I start?

The data exists in the background, and I need to find a way to update the chart so that Angular properly acknowledges the data changes.

Answer №1

Seeking an authentic resolution, I consulted the primary source for guidance. It was revealed to me that after version 4.0.0-rc.1, the behavior of the charts had been modified. After installing this version and following a provided example, I managed to achieve the desired outcome.

   updateData() {
            this.updatedData = {
                labels: ['A', 'B', 'C'],
                datasets: [
                    {
                        data: [150, 300, 100],
                        backgroundColor: [
                            "#f44250",
                            "#c4f441",
                            "#f49541"
                        ],
                        hoverBackgroundColor: [
                            "#f44250",
                            "#c4f441",
                            "#f49541"
                        ]
                     }]
            }
            this.data = Object.assign({}, this.changedData);

}

https://github.com/primefaces/primeng/issues/2235

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

Testing TypeScript using Jasmine and Chutzpah within Visual Studio 2015

I am new to unit testing in AngularJS with TypeScript. I have been using jasmine and chutzpah for unit testing, but I encountered an error "ReferenceError: Can't find variable: angular". My test file looks like this: //File:test.ts ///<chutzpah_r ...

How do Angular and NestJS manage to dynamically resolve injection tokens during runtime using the TypeScript type hints provided at compile time?

Frameworks such as Angular and NestJS in TypeScript utilize dependency injection by converting TypeScript type hints into injection tokens. These tokens are then used to fetch dependencies and inject them into constructors at runtime: @Injectable() // < ...

Is there a way to extract both a and b from the array?

I just started learning programming and I'm currently working on creating an API call to use in another function. However, I've hit a roadblock. I need to extract values for variables a and b separately from the response of this API call: import ...

Exploring the power of Angular 2 with Jasmine tests

Recently, I have been studying the guide on testing in Angular 2 using Jasmine as outlined in the tutorial found at https://angular.io/docs/ts/latest/guide/testing.html. Specifically, I have been working on incorporating Jasmine with Angular 2 by following ...

Tips for using a loop variable as an argument in a method call for an attribute reference

Within the html code of my component, I have the following: <div *ngFor="let image of images; let i=index;" class="m-image-wrapper"> <i class="fa fa-times m-delete-img" (click)="removeImage(i, {{image.docname ...

Exploring Angular 4: Iterating Over Observables to Fetch Data into a Fresh Array

Context Currently, I am in the process of developing a find feature for a chat application. In this setup, each set of messages is identified by an index. The goal of the `find()` function is to retrieve each message collection reference from the `message ...

The matInput value remains stagnant and fails to update

I am encountering an issue with a form Input field for username and password. Here is the code snippet: <mat-form-field class="mdb-form-field-modal form-adjustments"> <input (keydown)="emailBtnFocus($event)" tabindex="0" matInput placeholder ...

Creating a personalized 404 page in your Angular Project and configuring a route for it

I am currently working on an Angular project that includes a component named 'wrongRouteComponent' for a custom 404 page. Whenever a user enters a non pre-defined route, the 'wrong-route.component.html' should be displayed. However, I a ...

Create a new object containing a series of function expressions, but exclude the first function parameter

In my current setup, I have a variable called storePattern const storePattern = { state: { }, mutations: { }, actions: {}, modules: { modal: { actions: { openModal(store, name: string): boolean { console.log('Op ...

Navigating through an array containing references to object IDs with Mongoose

In my meanjs project, I am receiving user input on the server with a specific request body structure: { transaction: { heading: '', items: [Object] }, something: {}, somethingAgain: {} } The format of the items a ...

The Angular CLI release does not match the Angular version

After updating Angular to version 9, my previously smoothly running angular project started throwing this error: This peculiar error message popped up: This version of CLI is only compatible with Angular versions 0.0.0 || ^10.0.0-beta || >=10.0.0 <1 ...

Sass-loader in Webpack fails to recognize the use of '@' symbol and raises an error

I am facing an issue with loading a SCSS file through webpack. It seems like many others are experiencing the same problem without any clear explanation. Essentially, I am encountering this error: ERROR in ./src/app/theme.scss Module parse failed: C:&bso ...

Using Angular 2 to showcase icons in the navbar post authentication

The structure of my components is as follows: The app component contains a navigation bar and router outlet. The navigation bar includes a logo, generic links, and specific links that are only shown after user login and authentication. The router outlet de ...

The object prototype can only be an instance of an Object or null; any other value will

While attempting to create a codesandbox in order to replicate a bug, I encountered an additional issue. You can view my codesandbox here: https://codesandbox.io/s/vue-typescript-example-o7xsv The error message states: Object prototype may only be an ...

Creating dynamic HTML with Angular 2 using property binding

After retrieving an HTML string from the database, I came across html='<span>{{name}}</span>' where 'name' is a component property. I am looking to display this string in HTML while maintaining the name binding. I have expl ...

How can I set an array as a property of an object using the Angular Subscribe method?

I'm attempting to retrieve array values from the en.json translation file in Angular and then bind them to an object property using the code snippet below. Here is the TypeScript code: ngOnInit() { this.en = { dayNamesMin: this.translateS ...

Is it possible for the binding model of Mat-Checkbox to be optional or null?

Greetings everyone! I am a newcomer to the world of Angular, where I have successfully created a dynamic list of checkboxes. However, I have encountered a challenge when trying to bind selected values from an API to these checkboxes. <div *ngFor="let b ...

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...

I am facing an issue where I am unable to execute 'npm run server' after compiling an Angular app using 'npm run

I encountered an issue with my Angular app that is utilizing Angular Universal. After bundling the app using npm run build:prod, everything seemed to be fine without any errors. However, when I attempted to view the app in the browser by running npm run se ...

Establish a connection with MongoDB and make changes to the data

I am facing an issue while trying to update values stored in MongoDB. I thought of using mongoose to view and edit the data, but it seems like I'm encountering an error along the way. Has anyone successfully implemented this kind of task before? impo ...