Reputation: 651
I am experimenting with ng2-charts using Angular 2. I started by following the example to create a line chart. It initialises the chart using a dataset as follows:
public lineChartData:Array<any> = [
{data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
{data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'},
{data: [18, 48, 77, 9, 100, 27, 40], label: 'Series C'}
];
I want to progess by retrieving data from a server - this works, however I no longer want a hardcoded initial dataset. If I change lineChartData
to be empty, I get the following error:
ERROR Error: ng-charts configuration error,
data or datasets field are required to render char line
Stack trace:
../../../../ng2-charts/charts/charts.js/BaseChartDirective.prototype.getDatasets@http://localhost:4200/vendor.bundle.js:31447:19
../../../../ng2-charts/charts/charts.js/BaseChartDirective.prototype.getChartBuilder@http://localhost:4200/vendor.bundle.js:31375:24
../../../../ng2-charts/charts/charts.js/BaseChartDirective.prototype.refresh@http://localhost:4200/vendor.bundle.js:31457:22
../../../../ng2-charts/charts/charts.js/BaseChartDirective.prototype.ngOnInit@http://localhost:4200/vendor.bundle.js:31346:13
The only way I have been able to get round this is to add empty objects in lineChartData. But this places a constraint on how much data I can return. Currently, I am not sure how much data needs to be returned, or if this is arbitrary.
Is there a way of having an empty initial dataset which is populated when data is retrieved from server?
Upvotes: 4
Views: 6549
Reputation: 363
Use *ngIf when the dynamic data comes in "barChartData" array then it will work.
<div style="display: block" *ngIf="barChartData">
<canvas baseChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[legend]="barChartLegend"
[chartType]="barChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
Upvotes: 2