Skip to content Skip to sidebar Skip to footer

Update Charts In Chartjs And Angular

I have the problem with update chart js in angular. I am using for it ngrx store. In selector subscriber (run in ngOnInit) I tried update the chart data: this.yrSubscription = this

Solution 1:

When using ng2-charts, there's no need to invoke chart.update(), let Angular change detection do its job. In case it doesn't work as expected, reassign the data array after pushing a new value to it. This can be done using Array.slice() as shown below.

this.yrSubscription = this.userDataStore.pipe(select(selectYrReport))
  .subscribe(el => {
    el.sessions.forEach(item => {
      this.datasetsSessions[0].data.push(+item);
      this.datasetsSessions[0].data = this.datasetsSessions[0].data.slice();
    });
  }); 

But the main issue is probably located in the _registerCustomChartJSPlugin method. Instead of defining such a method, define its content in a chartPlugins variable as follows:

chartPlugins = [{
  afterDatasetsDraw: (chart, easing): any => {
    ...
  }
}];

Inside the HTML template, you then have to provide chartPlugins as follows.

<canvas baseChart
  [datasets]="datasetsSessions"
  [plugins]="chartPlugins"
  ...
</canvas>

Please have a look at this StackBlitz.

Solution 2:

Assuming that you are registering the charts in the same component . First of all you need to keep a reference to your custom chart. In your component add this in your component class

customChartInstance : Chart;

Then in your afterDatasetsDraw add this.customChartInstance=chart

then in your subscription add

this.chart.update();

Solution 3:

Above Component Decorator have this :-

varrequire: any;
var Chart = require('chart.js');

In component have a property for keeping instance of chart

public chart: Chart;

First you need to understand is that Chart.plugins.register will only register a plugin globally for all charts. https://www.chartjs.org/docs/latest/developers/plugins.html#global-plugins

You need a chart for this plugin to apply

Lets Say you have a Canvas in your HTML like :-

<div><canvasid="canvas">{{ chart }}</canvas></div>

You need to update your inside ngoninit to ngrx Subscription To create a new chart if its not available.

ngOnInit() {
this._registerCustomChartJSPlugin();
this.yrSubscription = this.userDataStore.pipe(select(selectYrReport))
  .subscribe(el => {
      if(!this.chart) {
        this.createChart();
      }
    el.sessions.forEach(item => {
      this.datasetsSessions[0].data.push(+item);
    });
    this.chart.update();
  });
}
public createChart() {
   this.chart = new Chart('canvas'); //Include if any object required as second Parameter
}

Post a Comment for "Update Charts In Chartjs And Angular"