I am using Chart.js in Angular. When I choose a date in a web app calendar, rest service sends response, chart is updated, x and y axis. On my x axis I have dates as strings. However, if my response has less data then before, (not every month has same number of days or not every response has equal number of data), x axis doesnt shrink.
This:
this.barChartLabels = this.xLabels; //an array with many elements
if (selectedDateFormated === "2021-9-28") {
this.barChartLabels = ["a","b","c","d"]; // overwrite for demo purpose
}
will give something like this:
It should be only a,b,c,d on x axis. How to do that?
I have this in my subscribe() method to delete previous data, before updating them again from rest api:
this.barChartLabels = [];
this.barChartData[0].data = [];
this.barChartData[1].data = [];
this.xLabels = [];
this.Consumption = [];
this.Flow = [];
this.chart.update();
this.resultSet.result.forEach(item => {
this.xLabels.push(
item.a
);
this.Flow.push(
+item.b //+ is casting string to number
);
this.Consumption.push(
+item.f
);
});
this.barChartLabels = this.xLabels;
this.barChartData[0].data = this.Consumption;
this.barChartData[1].data = this.Flow;
this.chart.chart.config.data.labels = this.xLabels;
This above did the trick. And the chart is a reference to a chart in a view:
@ViewChild(BaseChartDirective, { static: true }) chart: BaseChartDirective;
Don't know what this.chart.chart.config it actualy does and why. It's something about a bug in ng2-charts.. So I made this two methods and called them at the end of subscribe() method when response from api is pushed in my arrays.
refresh_chart() {
setTimeout(() => {
console.log("xLabels: " + this.xLabels);
console.log("Consumption: " + this.consumption);
if (this.chart && this.chart.chart && this.chart.chart.config) {
this.chart.chart.config.data.labels = this.xLabels;
this.chart.chart.config.data.datasets[0].data = this.consumption;
this.chart.chart.update();
}
});
}
clearCharts() {
this.barChartLabels= [];
this.emptyChartData(this.barChartData);
}
emptyChartData(obj) {
obj[0].data = [];
obj[1].data = [];
}