How to update data chart in async way in angular chart.js??

by haylee.mertz , in category: Javascript , 10 months ago

How to update data chart in async way in angular chart.js??

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 10 months ago

@haylee.mertz 

You can update a data chart in an asynchronous way in Angular using Chart.js by calling the update method on the Chart object after updating the data. Here is an example of how you can achieve this:

  1. First, make sure you have imported Chart.js and ng2-charts in your Angular application. npm install chart.js npm install ng2-charts
  2. In your component file, import the necessary modules and set up the chart data and options:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Component, OnInit } from '@angular/core';
import { ChartDataSets, ChartOptions } from 'chart.js';
import { Color } from 'ng2-charts';
import { Chart } from 'chart.js';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {

  lineChartData: ChartDataSets[] = [
    { 
      data: [65, 59, 80, 81, 56, 55, 40],
      label: 'Sample data'
    }
  ];

  lineChartLabels: string[] = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

  lineChartOptions: ChartOptions = {
    responsive: true,
  };

  lineChartColors: Color[] = [];

  lineChartLegend = true;
  lineChartType = 'line';
  lineChartPlugins = [];

  chart: any;

  constructor() { }

  ngOnInit(): void {
    this.chart = new Chart('canvas', {
      type: 'line',
      data: {
        labels: this.lineChartLabels,
        datasets: this.lineChartData
      },
      options: this.lineChartOptions
    });
  }

  updateChartData() {
    // Simulate asynchronous data update
    setTimeout(() => {
      this.lineChartData[0].data = [28, 48, 40, 19, 86, 27, 90];
      this.chart.update();
    }, 2000);
  }

}


  1. In your HTML template, add the canvas element to render the chart:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<div style="display: block;">
  <canvas baseChart
          id="canvas"
          [datasets]="lineChartData"
          [labels]="lineChartLabels"
          [options]="lineChartOptions"
          [colors]="lineChartColors"
          [legend]="lineChartLegend"
          [chartType]="lineChartType"
          [plugins]="lineChartPlugins">
  </canvas>
</div>

<button (click)="updateChartData()">Update Chart Data</button>


In this example, we have a line chart with initial data. When the updateChartData method is called, it updates the chart data after a 2-second delay. The chart.update() method is called to apply the changes to the chart.


This way, you can update the data chart in an asynchronous way in Angular using Chart.js.