Angular2 Update Tagged ng2 Charts

I am starting to work these days with Angular2 and asking a question with the ng2-charts framework.

Here is my component.ts code:

import { Component } from '@angular/core'; import { ChartsModule } from 'ng2-charts'; import { PredictionService } from './prediction.service' @Component({ selector: 'prediction-result-chart', templateUrl: './predictionResultChart.component.html' }) export class PredictionResultChartComponent{ public pieChartLabels:string[] = []; public pieChartData:number[] = []; public pieChartType:string = 'pie'; public JSONobject = {} constructor(private predictionService: PredictionService){ this.getPredictions(); } public getPredictions() { this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe(); } public populateChart(obj): void{ let labels:string[] = []; let data:number[] = []; for (var i = 0; i < obj.predictions.length; i++) { labels.push(String(obj.predictions[i].class)); data.push(obj.predictions[i].percentage); }; this.pieChartData = data; this.pieChartLabels = labels; } public chartClicked(e:any):void {} public chartHovered(e:any):void {} } 

Code component.html :

 <div style="display: block"> <canvas baseChart [data]="pieChartData" [labels]="pieChartLabels" [chartType]="pieChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"></canvas> </div> 

Service Code:

 import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class PredictionService { private baseUrl: string = 'http://localhost:8080/predict/'; constructor(private http : Http){ } getPredictions(text :string) { return this.http.get(this.baseUrl + text).map(res => res.json()); } } 

With the codes above, here is what I have a chart without any colors: enter image description here

In fact, when I looked deeply into my code, the HTML component took the variables at the beginning and then updated them. Therefore, when the tags are empty, even if I add several tags, they will be added as undefined. Therefore, I have a chart with the correct values, but not with the correct labels. Everything is marked as undefined.

And if I start creating labels at the beginning, I will have a nice color chart with the correct values

So my questions are:

How to load data, then display the HTML component?

In any case, to process the chart.js component without data and update it with the correct labels and data?

Any help needed, thanks.

+4
javascript angular charts ng2-charts
source share
4 answers

In standard chart.js, you can use the .update() prototype method to re-render the chart after you have changed your data (including labels).

However, it seems that the ng2 diagrams do not provide a mechanism for triggering the update (according to this github question ). I'm generally not very experienced in Angular2, but maybe this will work for you? The approach was taken from a comment made by zbagley in a github release published 17 days ago (unfortunately, I could not find a way to create a URL linking to this particular comment).

The approach basically does not display your chart until the data is available. The following is the change to component.ts code.

 import { Component } from '@angular/core'; import { ChartsModule } from 'ng2-charts'; import { PredictionService } from './prediction.service' @Component({ selector: 'prediction-result-chart', templateUrl: './predictionResultChart.component.html' }) export class PredictionResultChartComponent { public pieChartLabels:string[] = []; public pieChartData:number[] = []; public pieChartType:string = 'pie'; public JSONobject = {}; public isDataAvailable:boolean = false; constructor(private predictionService: PredictionService){ this.getPredictions(); } public getPredictions() { this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe(); } public populateChart(obj): void { let labels:string[] = []; let data:number[] = []; for (var i = 0; i < obj.predictions.length; i++) { labels.push(String(obj.predictions[i].class)); data.push(obj.predictions[i].percentage); }; this.pieChartData = data; this.pieChartLabels = labels; this.isDataAvailable = true; } public chartClicked(e:any):void {} public chartHovered(e:any):void {} } 

And then you will use ngIf in the component.html code.

 <div style="display: block" *ngIf="isDataAvailable"> <canvas baseChart [data]="pieChartData" [labels]="pieChartLabels" [chartType]="pieChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"></canvas> </div> 
+11
source share

I can get the values ​​when I print to the console, but not displayed on the chart.

 this.pieChartLabels :: ['PayDirect agent deposit','GtCollections agent deposit','Quickteller agent deposit'] this.pieChartData :: [1990,1202,2476] 

Is there any way to update the chart. It seems that the map was loaded before the data was received from the web service.

 isDataAvailable2 = true 

but the chart never loads.

+1
source share

I updated the chart labels by updating the labels in the config property.

 import { Component } from '@angular/core'; import { ChartsModule } from 'ng2-charts'; import { PredictionService } from './prediction.service' import { BaseChartDirective } from 'ng2-charts'; // ----- added @Component({ selector: 'prediction-result-chart', templateUrl: './predictionResultChart.component.html' }) export class PredictionResultChartComponent { public pieChartLabels:string[] = []; public pieChartData:number[] = []; public pieChartType:string = 'pie'; public JSONobject = {}; public isDataAvailable:boolean = false; @ViewChild('mainChart') mainChart: BaseChartDirective; // ----- added constructor(private predictionService: PredictionService){ this.getPredictions(); } public getPredictions() { this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe(); } public populateChart(obj): void { let labels:string[] = []; let data:number[] = []; for (var i = 0; i < obj.predictions.length; i++) { labels.push(String(obj.predictions[i].class)); data.push(obj.predictions[i].percentage); }; this.pieChartData = data; this.mainChart.chart.config.data.labels = labels; // ---- updated this.isDataAvailable = true; } public chartClicked(e:any):void {} public chartHovered(e:any):void {} } 

In HTML add # {chartName} to access it

 <div style="display: block" *ngIf="isDataAvailable"> <canvas #mainChart="base-chart" baseChart [data]="pieChartData" [labels]="pieChartLabels" [chartType]="pieChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"></canvas> </div> 
+1
source share

first you’ll make sure that the order of the labels matches the order of data_set, so basically you have these two variables:

 private datasets_pie = [ { label: "Commissions", data: Array<any>(), backgroundColor: Array<any>() } ]; private labels_pie = Array<any>(); 

Secondly, I had the same problem with colors, so I had to manually insert colors, here is an example:

 private chartColors: any[] = [{ backgroundColor: ["#FFA1B5", "#7B68EE", "#87CEFA", "#B22222", "#FFE29A", "#D2B48C", "#90EE90", "#FF69B4", "#EE82EE", "#6A5ACD", "#b8436d", "#9ACD32", "#00d9f9", "#800080", "#FF6347", "#DDA0DD", "#a4c73c", "#a4add3", "#008000", "#DAA520", "#00BFFF", "#2F4F4F", "#FF8C00", "#A9A9A9", "#FFB6C1", "#00FFFF", "#6495ED", "#7FFFD4", "#F0F8FF", "#7FFF00", "#008B8B", "#9932CC", "#E9967A", "#8FBC8F", "#483D8B", "#D3D3D3", "#ADD8E6"] }]; 

finally, after creating this object correctly, you should call this function:

 setTimeout(() => { if (this.chart && this.chart.chart && this.chart.chart.config) { this.chart.chart.config.data.labels = this.labels_pie; this.chart.chart.config.data.datasets = this.datasets_pie; this.chart.chart.config.data.colors = this.chartColors; this.chart.chart.update(); } this.sommeStat = this.getSomme(); }); 

so I think this might work:

  import { Component, ViewChild, ElementRef } from '@angular/core'; import { ChartsModule } from 'ng2-charts'; import { PredictionService } from './prediction.service'; import { BaseChartDirective } from 'ng2-charts/ng2-charts'; @Component({ selector: 'prediction-result-chart', templateUrl: './predictionResultChart.component.html' }) export class PredictionResultChartComponent{ @ViewChild(BaseChartDirective) chart: BaseChartDirective; public pieChartType: string = 'doughnut'; //public lineChartType: string = 'line'; private datasets_pie = [ { label: "Commissions", data: Array<any>(), backgroundColor: Array<any>() } ]; private labels_pie = Array<any>(); //private datasets_line : LineData[] = []; // private datasets_line : { label : string, data : Array<any>}[] ; // private labels_line = Array<any>(); private chartColors: any[] = [{ backgroundColor: ["#FFA1B5", "#7B68EE", "#87CEFA", "#B22222", "#FFE29A", "#D2B48C", "#90EE90", "#FF69B4", "#EE82EE", "#6A5ACD", "#b8436d", "#9ACD32", "#00d9f9", "#800080", "#FF6347", "#DDA0DD", "#a4c73c", "#a4add3", "#008000", "#DAA520", "#00BFFF", "#2F4F4F", "#FF8C00", "#A9A9A9", "#FFB6C1", "#00FFFF", "#6495ED", "#7FFFD4", "#F0F8FF", "#7FFF00", "#008B8B", "#9932CC", "#E9967A", "#8FBC8F", "#483D8B", "#D3D3D3", "#ADD8E6"] }]; private options = { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }; public JSONobject = {} constructor(private predictionService: PredictionService){ this.getPredictions(); } public getPredictions() { this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe(); } public populateChart(obj): void{ this.labels_pie = []; this.datasets_pie[0]['data'] = []; for (var i = 0; i < obj.predictions.length; i++) { labels.push(String(obj.predictions[i].class)); this.datasets_pie[0]['data'].push(obj.predictions[i].percentage); }; let arrColors: any[]; arrColors = arrColorsCopy.splice(0, this.products.length); this.datasets_pie[0]['backgroundColor'] = arrColors; setTimeout(() => { if (this.chart && this.chart.chart && this.chart.chart.config) { this.chart.chart.config.data.labels = this.labels_pie; this.chart.chart.config.data.datasets = this.datasets_pie; this.chart.chart.config.data.colors = this.chartColors; this.chart.chart.update(); } }); } public chartClicked(e:any):void {} public chartHovered(e:any):void {} } 

for html it should look like this:

 <div class="col-md-8"> <div class="chart"> <canvas baseChart [datasets]="datasets_pie" [labels]="labels_pie" [chartType]="pieChartType" [colors]="chartColors"> </canvas> </div> </div> 

thats all, you should try this way, it should work

0
source share

All Articles