Utilizing PrimeNg with Angular 2 to dynamically update charts using @ViewChild

I'm currently utilizing Angular2 with PrimeNG for my application. My dashboard includes charts and after attempting to upgrade to PrimeNG rc7 (from rc5) where they addressed an issue with updating charts, I'm facing challenges updating my chart due to the changes that require calling a method.

Although I've come across the @ViewChild decorator, I'm unsure about its proper usage.

Here's a snippet of my chart.html:

<p-chart #linechart  type="line" #linechart
 id="linechart" [data]="ntwdata" [options]="options">
</p-chart>
...

I tried implementing @ViewChild in different ways but encountered issues with accessing the chart object for refreshing purposes. If any of you have suggestions or solutions, please explain it to me as if I were a beginner!

Thank you in advance!

Answer №1

<p-chart #graph type="line" [data]="graphData" [options]="settings"></p-chart>

next, in your Angular component

import { UIChart } from "primeng/components/chart/chart";

retrieve the view reference (replace "graph" with appropriate reference)

@ViewChild("chart") graph: UIChart; 

this.graph.reinitialize(); 

once you have assigned the values.

Answer №2

Make sure to keep the labels and datasets updated as well.

this.chart.data.labels = labels;
this.chart.data.datasets = datasets;

Consider adding a delay before refreshing the chart, such as 100ms or 1200ms.

This technique has been successful for me.

Answer №3

The new functionality can now be accessed by including the following code:

import { UIChart } from 'primeng/chart';

Alternatively, you can use refresh() as another method to update.

Answer №4

When I needed to change the graph type, this code snippet was quite effective for me.

    HTML :
    
    <select class="form-control type-selection" (change)="onSelection($event)" style="position: absolute;">
    <option *ngFor="let item of ntwdata" [value]="item.value">{{item.label}}</option> 
    </select>
    <p-chart #linechart  type="line" #linechart id="linechart" [data]="ntwdata [options]="options"></p-chart>


Component :




import { NTWDATA } from '../resources/mock/chartdata'
import { UIChart } from "primeng/components/chart/chart";

@ViewChild('chart', { static: false }) chart: UIChart;
type: any = 'doughnut';
graphType: any;

ngOnInit() {    
    this.ntwdata = NTWDATA ;
    this.graphType = [
      { value: 'doughnut', label: 'doughnut' },
      { value: 'pie', label: 'pie' },
      { value: 'line', label: 'line' }
    ];
  }

onSelection(event) {
    this.type = event.target.value;
    this.ntwdata.type = this.type; //doughnut, Pie, Line
    setTimeout(() => { 
      this.chart.reinit();
    }, 100);
  }
Remember to use reinit() within a setTimeout method after setting the value.

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

Nested MD-list-item in Angular 2 Material

Trying to implement nested lists in a sidenav using Angular 2 with material design. Here is the initial code: <md-sidenav #sidenav class="sidenav" mode="over" opened> <md-nav-list> <md-card class="user-card"> ...

The values of object keys are printed in a random order

Hey everyone, I have an object that looks like this var dates = { '2021-09-15': 11, '2021-09-16': 22, '2021-09-17': 38, '2021-09-18': 50, '2021-09-19': 65 }; I am trying to display the valu ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

Trouble with Nested Routing in React Router Version 6: Route not Rendering

I'm facing issues nesting a path within another path in react-router-dom version 6. When I try to visit the nested argument's page (/blog/1), it shows up as a blank non-styled HTML page. However, when I add a child path to the root like /blog, it ...

How can I implement email authentication in Angular using Firebase?

After only a month of playing around with Angular, I have managed to develop a web app with login and signup forms using Firebase for data storage and authentication. Typically, new users are required to sign up before logging in. However, I now face a di ...

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

Error: The recursive list cannot access the 'length' property of an undefined value

I am experiencing an issue with my recursive list, as I am unable to retrieve the entire list. <ul> <ng-container *ngTemplateOutlet="recursiveListTmpl; context:{ list: famillies }" ></ng-container> </ul> <ng-te ...

Ensure that the query value remains constant in Express.js

Issue: The query value is changing unexpectedly. // url: "http://localhost:4000/sr?q=%C3%BCt%C3%BC" export const search = async (req: Request, res: Response) => { try { const query = String(req.query.q) console.log("query: &quo ...

When the value is empty, MUI Autocomplete will highlight all items

I have encountered a specific issue. I am working on developing a custom Autocomplete Component for filtering purposes. However, I recently came across the following Warning. MUI: The value provided to Autocomplete is invalid. None of the options matc ...

What is the best method to reset values in ngx-bootstrap date picker?

At the moment, it is only accepting the most recently selected values. To see a live demo, click here. ...

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

Is there a marble experiment that will alter its results when a function is executed?

Within Angular 8, there exists a service that contains a readonly Observable property. This property is created from a BehaviorSubject<string> which holds a string describing the current state of the service. Additionally, the service includes method ...

Having trouble with Nextjs API Integration - encountering error 404

I'm currently facing a major issue and I've hit a dead end. I've been spending days trying to connect my local nextjs 14 app to the CVENT API, but I keep receiving a persistent 404 error. Here's what is displayed in the frontend console ...

What steps should be taken to resolve the error message "This Expression is not constructable"?

I'm trying to import a JavaScript class into TypeScript, but I keep getting the error message This expression is not constructable.. The TypeScript compiler also indicates that A does not have a constructor signature. Can anyone help me figure out how ...

"Implementing an Angular unit test for a method that calls a service

**I am trying to test the following method using Jasmine & Karma. The requirement is to cover all lines of code. However, I am struggling to achieve full code coverage. Any suggestions on how to approach this?** I attempted calling the method directly, bu ...

A technique for deactivating reactive forms control within a nested formArray

Is there a way to selectively disable individual controls within the 'fields' group which is nested under this.form.get('groups').controls? I know how to disable an entire group by using this.form.get('groups').controls.disabl ...

pnpm, vue, and vite monorepo: tackling alias path imports within a workspace package

I am in the process of creating a monorepo for UI applications that utilize shared components and styles with pnpm, typescript, vue, and vite. While attempting to streamline development and deployment using pnpm's workspace feature, I am encountering ...

Cannot see the template on the Angular Typescript component

After encountering and resolving this issue: AngularJS directive not displaying the template I decided to experiment with an Angular component and TypeScript, but unfortunately, I can't seem to make it work. The component refuses to display. This is ...

The functionality of Angular Material Chip is encountering issues when paired with Angular 7

Issue with Angular Material Chip module compatibility in Angular version 7 Tech: Using Angular version 7, angular cli, and angular material Desired Outcome: Looking to successfully implement the angular material chip module Steps taken so far: Insta ...

Executing initial function in Angular 2 before the first routing takes place

I'm working on an app that needs to load all messages from the server before fully launching. Currently, I have placed the HTTP request in my app component's OnInit method. However, I am facing an issue where the routing does not wait for the d ...