Angular2 Update ng2-charts with labels

谁说胖子不能爱 提交于 2019-12-01 05:54:35

In standard chart.js you can use the .update() prototype method to re-render a chart after you have modified its data (including labels).

However, it appears that ng2-charts doesn't provide a mechanism to trigger the update (as per this github issue). I'm not very experienced in Angular2 at all, but perhaps this will work for you? The approach was taken from a comment made by zbagley in the github issue posted 17 days ago (unfortunately I could not find a way to generate a url referencing this specific comment).

The approach is to basically not render your chart until the data is available. Here is the change to your 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 would use ngIf in your 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>

I can get the values when i print to console but does not display on the chart.

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

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

isDataAvailable2 = true

but the chart never loaded.

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>

first you to be sure that the order of labels is matching the order of the data_set, so basicly 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 issue with the colors, so i had to insert the colors manually, 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 these object properly, you have to 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 that 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 the html it should be looking 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!