Updating the displayed data of an angular2-highcharts chart

I am facing an issue with rendering an empty chart initially and then updating it with data. The charts are rendered when the component is initialized and added through a list of chart options. Although the empty chart is successfully rendered, I am struggling to redraw it with updated data. I am attempting to populate the chart with data from a service using promises (adding dummy values for reference).

app.component.ts

import { Component, AfterViewInit } from '@angular/core';
import { ChartModule } from 'angular2-highcharts';

import { configs } from './configs';

@Component({
    selector: 'my-app',
    template: `
<div *ngFor="let chart of charts">
    <div #chart></div>
</div>`
})
export class AppComponent {
  charts = [];
  constructor(){}

  ngOnInit(): void{
      configs.forEach(config => {
          //Add charts
          this.charts.push(config);
      });

  }

  ngAfterViewInit(): void {
      this.charts.forEach(chart => {
          chart.series.push({
                          name: 'Installation',
                          data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
          });
      });
  }
}

configs.ts

export const configs = [
    {   
        chart:{
            type:'line',
            renderTo: 'line_chart'
        },
        chartName : 'abc',
        title : {text : ''},
        tabHolder : {'id':'line_chart','heading':'Line Chart'},
        xAxis:{categories:[]},
        plotOptions: {
            line: {
                dataLabels: {enabled: true},
            }
        },
        series: []
    },
    {
        chart:{
            type:'bar',
            renderTo: 'bar_chart'
        },
        chartName : 'xyz',
        title: {text: ''},
        tabHolder : {'id':'bar_chart','heading':'Bar Chart'},
        xAxis: {
            categories: [],
            title: {
                text: null
            }
        },
        yAxis: {
            min: 0,
            title: {text: ''},
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            }
        },
        series: []
    }
]

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ChartModule } from 'angular2-highcharts'
import { HighchartsStatic } from 'angular2-highcharts/dist/HighchartsService';
import { AppComponent } from './app.component';

declare var require: any;
export function highchartsFactory() {
  return require('highcharts');
}

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    ChartModule,
  ],
  providers: [{
      provide: HighchartsStatic,
      useFactory: highchartsFactory,
    }],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №1

If you're using angular2-highcharts, it appears to simply serve as a thin wrapper for Highcharts. The documentation demonstrates how to access the underlying native chart.

For the template:

<chart [options]="options" 
    (load)="saveInstance($event.context)">
</chart>

In the component:

saveInstance(chartInstance) {
    this.chart = chartInstance;
}

If you have an array of charts, you may want to pair your initial options with their respective native charts.

Template:

<div *ngFor="let chart of charts">
    <chart [options]="chart.options" 
        (load)="saveInstance($event.context, chart)">
    </chart>
</div>

Component:

 ngOnInit(): void{
      configs.forEach(config => {
          //Add charts
          this.charts.push({
              options: config,
              nativeChart: null // To be obtained with saveInstance
          });
      });
  }

saveInstance(chartInstance, chart) {
    chart.nativeChart = chartInstance;
}

Then utilize the native API to add your series and redraw:

ngAfterViewInit(): void {
    this.charts.forEach(chart => {
        chart.nativeChart.addSeries({
            name: "...",
            data: [...]
        }, 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

Angular Application cannot locate the interface file

Attempting to create a basic test environment for the OMBD Api. Utilizing an interface file named ombdresponse.ts: interface IOMBDResponse { Title: string; Year: string; Director: string; Poster: string; } The issue arises within the ombd- ...

Ways to duplicate a column value in a reusable table

Hi there! Currently, I am implementing a smart table (i.e reusable table) in our application. I need to send data through settings from one component file and retrieve it in the reusable component. However, I am facing an issue with binding nested values i ...

Addressing command problems in Angular

I am experiencing an issue with a dropdown functionality. When a user selects an option and then presses either the "Delete" or "Backspace" button on the keyboard, the value from the dropdown clears which is working correctly. However, I am attempting to i ...

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

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

What is the best way to include additional text in a dropdown menu?

I'm trying to add the text "Choose Country" in a drop-down list before the user selects their country. example1 Here is the line of code I used: <option data-hidden="true"> Choose Country </option> However, the phrase does ...

The concept of TypeScript usage within the `mui-x` DataGrid while calling the `useGridApiRef()` function

Could someone please help me understand the syntax used in this code snippet from mui/mui-x? export declare const useGridApiRef: <Api extends GridApiCommon = GridApiPro>() => React.MutableRefObject<Api>; My interpretation is that it exports ...

Transferring data between unrelated components

I am facing an issue where I am unable to pass a value from the Tabs component to the Task component. To address this, I have created a separate data service. The value in the Tabs component is obtained as a parameter from another component. However, when ...

Transforming the color of the navbar upon a scrolling action is implemented through Angular's [ngClass

New to Angular and looking to implement a feature where the navbar changes from transparent to dark upon scrolling. However, my current implementation keeps the navbar transparent even after scrolling. Any tips on achieving this functionality? Here is the ...

Angular Test Error: Refactoring requires a source file to be present

Trying to execute the command ng test, I encountered an error message. How can this issue be resolved? I am unsure of its meaning. ERROR in Must have a source file to refactor. To eliminate this warning, use "ng config -g cli.warnings.versionMismatc ...

Unable to reference the namespace 'ThemeDefinition' as a valid type within Vuetify

Looking to develop a unique theme for Vuetify v3.0.0-alpha.10 and I'm working with my vuetify.ts plugin file. import "@mdi/font/css/materialdesignicons.css"; import "vuetify/lib/styles/main.sass"; import { createVuetify, ThemeDefinition } from "v ...

Retrieving information as the user navigates to the next page

Currently, I am using an API endpoint that retrieves over 1000 data objects and delivers them to the user. I believe this method is not efficient since only 30 objects are displayed at once. Is there a more efficient way to load these objects, perhaps in ...

In TypeScript, combining the numbers 0 and 1 results in the value 01

I am in the process of developing a Shopping Card feature. private _card: Map<Product, number> = new Map<Product, number>(); ... addToCard(prod: Product, amount: number = 1): void { const totalAmount: number = this._card.get(prod) + amou ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...

Contrasting Dependency Injection with Exporting Class Instances

I've been diving into the world of TypeScript and working on enhancing my skills as a web developer. One project I'm currently focused on is a simple ToDo app, which you can find here: https://github.com/ludersGabriel/toDo/tree/dev/backend. My q ...

Angular 14 debug error: Incorrect base path setting

Whenever I go for a run, I have to specify a starting point such as /pis/ ng serve --serve-path /pis/ Even after following these instructions, nothing seems to load. Can anyone lend a hand with setting a starting point in the ng serve process? ...

Identify modifications in NGRX state before shutting down

In my Angular application, I am utilizing NGRX to manage state. Users are able to switch between different versions of the store, each saved and reloaded from a database. It's important for me to detect when changes have been made to the store but not ...

What is the significance of using the @Input decorator on a component property in Angular?

Within this particular component, I discovered the @Input decorator connected to the variable. @Input() description: string; The variable "description" is then utilized in the HTML as an interpolation. <div>{{description}}</div> This prompt ...

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

Importing Angular Circular Module for your project

I have encountered a situation where I have two Modules with components that need to use each other. This means that I have to import "word" in "test" and "test" in "word" which results in an error. How can I resolve this issue? Module "test": @NgModu ...