Pageviews

Friday, July 26, 2019

Chart.js or chart js update chart on Angular 2 and above

After burning a lot of hours finally got the perfect solution

Chart.js or chart js update chart Angular 2 and above


Follow Angular2-chartjs to create charts in Angular 2 and above.


Once your project is working as expected and you want to update the charts as per your desired data please follow below easy and simple steps -

1. Add your chart id in html file and add a method to land in your component.

<chart #monthlyChart [type]="typeItems" [data]="dataItems" [options]="optionsItems" (click)="updateItemCategory()"></chart>

for example -

#monthlyChart is chart id

and

(click)="updateItemCategory()" is for invoking the update method



2. In your app component - 

import { ChartComponent } from 'angular2-chartjs';

then inside component class 


@ViewChild(ChartComponent,{static:false}) monthlyChart: ChartComponent; 

private updateItemCategory(){
   setTimeout(() => {
       this.monthlyChart.chart.data.datasets[0].data = [565, 539, 680, 381, 556];
       this.monthlyChart.chart.data.labels =  ["January", "February", "March", "April", "May"];
       this.monthlyChart.chart.update();
   }, 10);
}

Done - Just run your project again and check ☺☺

References -
Angular2-chartjs

Angular2-chartjs_issues