Chartjs-Ng-charts not updating labels when chart data is updated at same time

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

<div class="chart">
            <canvas baseChart [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 class BarChartDemoComponent{
@ViewChild(BaseChartDirective) chart: BaseChartDirective;
      public barChartOptions :any = {
        scaleShowVerticalLines:false,
        responsive:true
      };
      //Labels
      public barChartLabel :string[];

      //Data
      public 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

Leave a comment