[Chartjs]-Update charts in chartjs and angular

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.

0👍

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();

-3👍

Above Component Decorator have this :-

var require: 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>
  <canvas id="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
}

Leave a comment