I am facing an issue with updating Chart.js in Angular while utilizing ngrx store.
When trying to update the chart data in the selector subscriber (executed in ngOnInit), I encountered the following code:
this.yrSubscription = this.userDataStore.pipe(select(selectYrReport))
.subscribe(el => {
el.sessions.forEach(item => {
this.datasetsSessions[0].data.push(+item);
});
});
This is my current chart data:
datasetsSessions: ChartDataSets[] = [{
label: 'Sessions',
data: [],
fill: false
}];
Chart registration:
private _registerCustomChartJSPlugin(): void {
(window as any).Chart.plugins.register({
afterDatasetsDraw: (chart, easing): any => {
if (!chart.options.plugins.xLabelsOnTop
|| (chart.options.plugins.xLabelsOnTop && chart.options.plugins.xLabelsOnTop.active === false)) {
return;
}
const ctx = chart.ctx;
chart.data.datasets.forEach((dataset, i): any => {
const meta = chart.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach((element, index): any => {
// Drawing text in white, with specific font details
ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
const fontSize = 13;
const fontStyle = 'normal';
const fontFamily = 'Roboto, Helvetica Neue, Arial';
ctx.font = (window as any).Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
const dataString = dataset.data[index].toString() + 'k';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const padding = 15;
const startY = 24;
const position = element.tooltipPosition();
ctx.fillText(dataString, position.x, startY);
ctx.save();
ctx.beginPath();
ctx.setLineDash([5, 3]);
ctx.moveTo(position.x, startY + padding);
ctx.lineTo(position.x, position.y - padding);
ctx.strokeStyle = 'rgba(255,255,255,0.12)';
ctx.stroke();
ctx.restore();
});
}
});
}
});
}
The function is called in the constructor of the component.
Even though I am aware that I need to run chart.update(), I keep encountering errors stating that the chart is undefined.