I am currently working on an Angular application using the ng2-charts
package. In one of my components, I have a pie chart displaying data retrieved from the server. Here is the code snippet for that component:
export class PieChartComponent implements OnInit {
data: Array<number> = [];
labels: Array<string> = ['', '', '', ''];
private line: string;
private department: string;
constructor(public dataService: LineService, private route: ActivatedRoute) {
this.route.params.forEach((params: Params) => {
this.department = params['dep'];
this.line = params['id'];
});
}
ngOnInit() {
this.dataService.getLineTAL(this.department, this.line).forEach(result => {
this.data = result.map(val => val.val);
this.labels = result.map(val => val.tag);
});
}
}
Here is the HTML corresponding to the component:
<div style="display: block">
<canvas baseChart [data]="data" [labels]="labels" [chartType]="'pie'" (chartClick)="chartClicked($event)" width="1" height="1"></canvas>
</div>
Upon debugging the application, I noticed that although the this.labels
array is correctly updated with the expected values for the chart data labels, the chart itself fails to display these values when hovered over. Instead, it shows empty tooltips.
Another issue I encountered is that all default colors in the chart have inexplicably turned grey. This happened after moving this functionality into its own component. Any insights on what might be causing this?
In an attempt to resolve the issues, I tried calling this.chart.ngOnChanges({});
where chart
is defined as
@ViewChild(BaseChartDirective) chart: BaseChartDirective;
before making the service call. I also experimented with this.labels = this.labels.slice();
at the end of the result mapping process to trigger a refresh, but unfortunately, neither solution proved effective.
Update:
Despite confirming that the ngAfterViewInit
event populates the chart object with accurate data and label properties, the chart continues to exhibit incorrect behavior. It still does not render as intended.