Skip to content Skip to sidebar Skip to footer

Ng-charts Not Updating Labels When Chart Data Is Updated At Same Time

My ng2-charts component is not updating its labels when I update the charts data at the same time in ngOnChanges(). If i comment out the data var update in ngOnChanges()the labels

Solution 1:

i think that the right way to update the chart, specially the line chart with multiple lines is to import ViewChild and ElementRef in your component, then you must import the BaseChartDirective to create an instance of your chart, then you can update your data and labels of the chart.

so first you have to give the class = "chart" for the chart in the html

<divclass="chart"><canvasbaseChart [datasets]="barChartData" [labels]="barChartLabel"  [options]="barChartOptions"></canvas></div>

if you notice i am using the datasets attribute to bind the data not the data attribute; now for the component you have to respect the structure of the data you're giving:

private datasets_lines: { label: string, data: Array<any> }[]

now the full code should be something like this:

import { Component, Input, OnInit, NgZone, OnChanges, ViewChild, ElementRef  } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';
    @Component({
      selector: 'app-bar-chart-demo',
      templateUrl: './bar-chart-demo.component.html',
      styleUrls: ['./bar-chart-demo.component.css'],
      inputs:['chartLabel', 'chartData']
    })
    export classBarChartDemoComponent{
@ViewChild(BaseChartDirective) chart: BaseChartDirective;
      public barChartOptions :any = {
        scaleShowVerticalLines:false,
        responsive:true
      };
      //Labelspublic barChartLabel :string[];

      //Datapublic barChartData: { label: string, data: Array<any> }[]=[];

      ngOnChanges(){ 
// do your changes here
setTimeout(() => {
       this.barChartData=this.chartData;
      this.barChartLabel=this.chartLabel;
            //console.log(this.barChartData);if (this.chart && this.chart.chart && this.chart.chart.config) {
                this.chart.chart.config.data.labels = this.barChartLabel;
                this.chart.chart.config.data.datasets = this.barChartData;
                this.chart.chart.config.data.options = this.barChartOptions;
                this.chart.chart.update();
            }
        });
      } 

       ngOnInit(){
         this.barChartLabel=['23 mei', '24 mei', '25 mei', '26 mei', '27 mei', '28 mei', '29 mei'];

         this.barChartData=[
         { data: [15, 29, 24, 21, 26, 15, 10], label: 'Opening/Time' },
         { data: [11, 20, 27, 26, 22, 17, 11], label: 'Closing/Time' }
     ];
       }
      }
    }

Note: you have to check that the number of the data equals the number of the labels

you can check my other exemple on this link ng2-charts update labels and data

Post a Comment for "Ng-charts Not Updating Labels When Chart Data Is Updated At Same Time"