I currently have a component in which i will be displaying multiple graphs on one page and each from a separate json file. I am using ng2-charts and angular2 and i am not sure how to have my graph load up based on json data and what is the best way of setting up multiple graph data in one component.
Here is my get call that returns an object in my component file:
dataType: any=[];
getData(){
this.dataService.getDataType().subscribe((response) => {this.dataType = response;
for(let item of this.dataType){
this.barChartLabels.push(this.dataType.name);
}
console.log(this.itemNames);
});
}
This is my code for loading my graph in component file:
public barChartOptions: any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels: any =[]; //LOAD from dataType.label
public barChartType: string = 'horizontalBar';
public barChartLegend: boolean = true;
public barChartData: any[] = //LOAD from dataType.data
Sample json data:
[
{
"id": 1,
"name": "Test 1",
"display": "Test 1",
"score": 45
}, ...
]
My html - using ng2-charts:
<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)">
</canvas>
Currently- i was able to see in the console that i have an array of labels but for some reason they are not being displayed on the graph even though i have pushed my returned labels into the barChartLabels array which is used in the html.
I also had the same problem when retrieving data and labels from my RESTful service into my charts. I resolved this problem by calling ngOnChanges() on the chart.
import { Component, AfterViewInit, OnInit, ViewChild, SimpleChanges } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts';
export class DashboardComponent implements OnInit, AfterViewInit {
@ViewChild(BaseChartDirective)
public chart: BaseChartDirective;
ngAfterViewInit() {
this.updateCharts();
}
public updateCharts(): void {
console.log('updateCharts()');
setTimeout(() => {
this.chart.ngOnChanges({} as SimpleChanges);
}, 100);
}
}
Update:
There was problems with loading a second chart witin the same component when using the above approach.
The ngOnChanges() will only update/load the first chart.
Instead I used the ngIf directive within each canvas and all charts load now.
<canvas baseChart *ngIf="pastChartLabels.length > 0" [colors]="pastChartColors" [datasets]="pastChartData" [labels]="pastChartLabels" [options]="pastChartOptions"
[chartType]="pastChartType" [legend]="pastChartLegend" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"></canvas>
<canvas baseChart *ngIf="recentChartLabels.length > 0" [colors]="recentChartColors" [datasets]="recentChartData" [labels]="recentChartLabels" [options]="recentChartOptions"
[chartType]="recentChartType" [legend]="recentChartLegend" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"></canvas>