Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ng2-charts / chart.js - how to refresh/update chart - angular 4

html:

<canvas *ngIf="actionData" baseChart width=800 height=300
                                  [datasets]="lineActionData"
                                  [labels]="lineActionLabels"
                                  [options]="lineChartOptions"
                                  [colors]="lineChartColors"
                                  [legend]="lineChartLegend"
                                  [chartType]="lineChartType"
                                  (chartHover)="chartHovered($event)"
                                  (chartClick)="chartClicked($event)"></canvas>

component:

public lineChartData:Array<any> = [
    {data: [], label: ''}
     {data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
     {data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'},
     {data: [18, 48, 77, 9, 100, 27, 40], label: 'Series C'},
  ];
etc

I have created a chart in html. In my *.ts file I have variables with data and options. Then I call a method which updates lineActionData. I have searched the internet but have not found how to UPDATE/REDRAW the chart. If I change the chart's type with a button (ie from line to bar and again to line), then the chart redraws itself with the new data. But how to do it straight after updating the values of data variable? All the methods that I found were not suited for my solution. Thx for help

like image 471
żyńy Avatar asked Dec 19 '22 01:12

żyńy


1 Answers

Please follow this and it will work!

1) Import these ones...

import { Component, OnInit, ViewChild } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts';

2) Into the export class (in your ts file) add this...

@ViewChild(BaseChartDirective) chart: BaseChartDirective;

then, first you should initialize the object that contains the data and label info. 1, 1, 1 is an example, you can use 0 if want...

public barChartData: any[] = [{
    data: [1,1,1,1,1,1,1],
    label: 'this is an example'
}];

3) in your ngOnInit method add a setTimeout function, or use the call to the backend by http;

setTimeout(() => {
    this.chart.chart.data.datasets[0].data = [55, 355, 35, 50, 50, 60, 10]
    this.chart.chart.update()
}, 2000);

4) in your html file, make sure to add baseChart to the canvas tag

 <div class="chart-wrapper">
  <canvas baseChart class="chart"
  [datasets]="barChartData"
  [labels]="barChartLabels"
  [options]="barChartOptions"
  [legend]="barChartLegend"
  [chartType]="barChartType"
  [colors]="chartColors"
  (chartHover)="chartHovered($event)"
  (chartClick)="chartClicked($event)">
  </canvas>
 </div>

5) just to explore a little more, in the ngOnInit method, you can perform a console.log of (this.chart.chart) and you will find more information about the object...

Hope it helps!

like image 108
Wal Heredia Avatar answered Dec 28 '22 10:12

Wal Heredia