Reputation: 290
I am using chart.js via ng2-charts to display a simple line chart that is fed with dynamic data whose X value is a timestamp. Therefore I am using the time cartesian axis of chart.js
When I start pushing data into the chart all is fine but I want to limit the amount of data shown to a max value, so I have implemented a simple mechanism where the oldest element is removed from the array as it gets filled.
This behavior seems to make the chart freeze and as a consequence shows this bug.
The problem is shown in this stackblitz: just wait a few seconds for the array to have three values (the max):
https://stackblitz.com/edit/ng2-charts-line-template-gzhikq
If I remove the "time" configuration from chart.js and feed the labels manually the problem does not show up (but this is not what I want!).
https://stackblitz.com/edit/ng2-charts-line-template-rs6enh
So the problem seems to be related to the usage of the time axis. I have tried the solutions explained in the bug mentioned above but none works (probably because they deal with the symptom not the root cause). Any help is greatly appreciated.
Upvotes: 0
Views: 1495
Reputation: 26150
In your code, you add an element to your data
array and remove the oldest one as soon as the limit of three entries is exceeded. The problem with this approach is that Angular doesn't notice changes in your data
array because its reference doesn't change and its size remains the same.
The issue can be solved by replacing the data
array inside ChartDataSets
each time the data changes. Instead of using Array.shift()
, you could use Array.slice()
.
lineChartData: ChartDataSets[] = [{
data: [],
label: 'Series A'
}];
...
ngOnInit() {
this.interval = setInterval(() => {
const data = this.lineChartData[0].data;
data.push({ y: Math.random(), x: new Date() });
this.lineChartData[0].data = data.slice(data.length > 3 ? 1 : 0);
}, 2000);
...
}
Please have a look at the following StackBlitz
Upvotes: 2