javascriptangularchart.jsbar-chartng2-charts

update data charts js Angular


This is my typescript code:

  public barChartData: ChartConfiguration<'bar'>['data'] = {
labels: [ '2006', '2007', '2008', '2009', '2010', '2011', '2012' ],
datasets: [
  { data: [ 65, 59, 80, 81, 56, 55, 40 ], label: 'Series A' },
  { data: [ 65, 59, 80, 81, 56, 55, 40 ], label: 'Series B' },
  { data: [ 28, 48, 40, 19, 86, 27, 90 ], label: 'Series C' }
]

};

HTML code:

<canvas baseChart            
                    [data]="barChartData"
                    [options]="barChartOptions"
                    [legend]="barChartLegend"
                    [type]="'bar'">
                </canvas>

so into UI i set radio group, day, month, yearly. When i click the radio i call another method who return the datasets:

    setBar() {
    
        this.barChartData.datasets = []
        this.barChartData.labels = []
    
        if(this.statisticsRes.length > 0) {
          let labelsSet: string[] = []
    
        if(this.optionTimer == environment.statisticTime.daily){
          labelsSet = this.getLast24Hours();
        } 
    
        if(this.optionTimer == environment.statisticTime.monthly){
          labelsSet = this.getLast30Days();
        } 
    
        if(this.optionTimer == environment.statisticTime.annual) {
          labelsSet = this.getLast12Months();
        }
    
        this.barChartData.labels = labelsSet
    
        // BAR
        this.barChartData.datasets = [
            { 
              data: this.statisticsRes.map((o) => o.travelcounter).reverse(), 
              label: 'Travelcounter' 
            },
            { 
              data: this.statisticsRes.map((o) => o.odometer).reverse(), 
              label: 'Odometer [m]' 
            },
            { 
              data: this.statisticsRes.map((o) => o.countoutofservice).reverse(), 
              label: 'Number of blocking errors' 
            }
          ]

// need here to update the charts
        }
        
      }

i need to update the data, but there is no: this.barChartData.update() or similar. How i can do?


Solution

  • You can try create a new memory reference (Objects are arrays are stored as references in memory, so even if we update the inner object properties, the memory reference will not change).

    We can use Object Destructuring so that angular recognizes the base object has changed and the chart get's refreshed.

    setBar() {
        ...
        // need here to update the charts
        this.barChartData = { ...this.barChartData }; // object destructuring creates new memory reference
    }
    

    Angular ng charts will notice this new memory reference and runs ngOnChanges, hopefully this call will update the chart with the latest data.