Chartjs-Angular ChartJs does not show Data for multiple Charts

0👍

Try this one

HTML

<div *ngFor="let chart of chartData">
    <canvas #chart></canvas>
</div>

Component

import { Component, ViewChildren, ElementRef, QueryList } from '@angular/core';

import { Chart } from 'chart.js';

const baseConfig: Chart.ChartConfiguration = {
  type: 'pie',
  options: {
    responsive: true,
  }
};

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChildren('chart', { read: ElementRef }) chartElementRefs: QueryList<ElementRef>;

  chartData: Chart.ChartData[] = [
    {
      labels: ['1500', '1600', '1700', '1750', '1800', '1850', '1900', '1950', '1999', '2050'],
      datasets: [{
        data: [86, 378, 106, 306, 507, 111, 133, 221, 783, 5000],
        borderColor: 'red',
        fill: false
      }]
    },
    {
      labels: ['1500', '1600', '1700', '1750', '1800', '1850', '1900', '1950', '1999', '2050'],
      datasets: [{
        data: [86, 378, 106, 306, 507, 111, 133, 221, 783, 5000].reverse(),
        borderColor: 'blue',
        fill: false
      }]
    }
  ];

  charts: Chart[] = [];

  ngAfterViewInit() {
    this.charts = this.chartElementRefs.map((chartElementRef, index) => {
      const config = Object.assign({}, baseConfig, { data: this.chartData[index] });

      return new Chart(chartElementRef.nativeElement, config);
    });
  }
}

Leave a comment