Angular2 Update ng2-charts with labels

前端 未结 4 861
旧巷少年郎
旧巷少年郎 2021-01-13 10:48

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

Here is my component.ts

4条回答
  •  逝去的感伤
    2021-01-13 11:22

    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

提交回复
热议问题