[Chartjs]-Ng2 chart multiple chart update

15👍

after some research I found the issue :
the issue is the:

@ViewChild( BaseChartDirective) chart: BaseChartDirective;

it only selects the first child, so

this.chart.chart.update()

only update the first child , the solution is: should use QueryList

@ViewChildren(BaseChartDirective) charts: QueryList<BaseChartDirective>;

and update the list :

  this.charts.forEach((child) => {
      child.chart.update()
  });

0👍

You don’t need to do this, create an data object and a labels object with in your current object. as you get your graph data from your data source you’ll probably have to modify it to fit the pattern of the graph that you have working, then iterate over all of your objects and plug in the graph data.

this all happens during a click event, I use Angular 8. Message me if you need help.

(properties in a model below)

public barChartData: any[] = [{ data: [], label: 'Red' }, { data: [], label: 'Blue' }],
public barChartLabels: any[] = [""]

this.redBlueCountByDate.forEach((item) => {

  barChartLabels.push(new Date(item.eomDate).toLocaleDateString("en-US"));
  barChartData[0].data.push(item.redDataCount);
  barChartData[1].data.push(item.blueDataCount);            
})

this.modelData.find(x => x.dataID == dataID).barChartData = barChartData;
this.modelData.find(x => x.dataID == dataID).barChartLabels = barChartLabels;

0👍

As it was said in other answer the update works only on the first chart. It seems that to update a chart you need to make a "clone" of its ChartDataSets and not just update the dataset or labels but reassign the whole variable.
You can see an issue on this case on github : https://github.com/valor-software/ng2-charts/issues/865

The solution to make it work :

//You have a dataset as an attribute of your component
public barChartData: ChartDataSets[] = [
  { data: [1, 2, 3], label: 'Approved', stack: 'a' },
  { data: [1, 2, 3], label: 'Accepted', stack: 'a' },
];
//In your update function just clone the dataset 
//Then update it with new data and reassign it to the attribute barChartData
update(){
  const clone = JSON.parse(JSON.stringify(this.barChartData));
  clone[0].data = data;
  this.barChartData = clone;
}

A stackblitz to demonstrate the answer I found : https://stackblitz.com/edit/ng2-charts-multiple-charts-tcc6ds?file=src%2Fapp%2Fapp.component.ts

Leave a comment