【问题标题】:Angular Chart.js Multiple CanvasAngular Chart.js 多画布
【发布时间】:2019-04-09 14:50:39
【问题描述】:

下面的代码只能用于图表,但我必须制作多个图表。如何使以下代码成为图表数组并在 Canvas 中使用 *ngFor 显示。

@ViewChild('pr_chart') chartElementRef: ElementRef;
ngAfterViewInit() {
  let ctx = this.chartElementRef.nativeElement;
  ctx = ctx.getContext('2d');

  this.chart = new Chart(ctx, {
    type: 'line',
    options: {
      legend: {
        display: false
      },
      scales: {
        xAxes: [{
          display: false
        }],
        yAxes: [{
          display: false
        }],
      }
    },
    data: {
      labels: [1500, 1600, 1700, 1750, 1800, 1850, 1900, 1950, 1999, 2050],
      datasets: [{
        data: [86, 378, 106, 306, 507, 111, 133, 221, 783, 5000],
        // label: "Africa",
        borderColor: '#3bd19c',
        fill: false
      }]
    }
  });
}
<canvas #pr_chart></canvas>

【问题讨论】:

  • 您是否尝试使用ViewChildren 而不是ViewChild 来获取匹配引用列表而不是单个引用?
  • 我对此不熟悉,你能分享一下这方面的例子吗?

标签: angular canvas chart.js ngfor


【解决方案1】:

您可以使用@ViewChildren 来获取&lt;canvas #pr_chart&gt;&lt;/canvas&gt; 实例的多个引用。我整理了一个示例,展示了如何使用上面的示例:https://stackblitz.com/edit/angular-chartjs-multiple-charts

基本上我的控制器上有一组图表元素:

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
    }]
  }
];

这些用于在我的模板中呈现多个图表:

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

您可以使用@ViewChildren 获取每个pr_chart 实例,而不是仅使用@ViewChild 获取单个引用:

@ViewChildren('pr_chart', { read: ElementRef }) chartElementRefs: QueryList<ElementRef>;

一旦我们有了这些引用,我们就可以遍历它们,通过使用该引用和相关数据来创建适当的图表:

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

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

由于在我的示例中,我将复制每个图表的大部分配置并且只有数据发生变化,因此我创建了一个基本配置,在渲染每个图表时共享它:

const baseConfig: Chart.ChartConfiguration = {
  type: 'line',
  options: {
    responsive: true,
    maintainAspectRatio: false,
    legend: { display: false },
    scales: {
      xAxes: [{ display: false }],
      yAxes: [{ display: false }],
    }
  }
};

【讨论】:

  • 多个图表在静态数据时可以正常工作,但图表数据是动态添加的,没有显示图表
猜你喜欢
  • 1970-01-01
  • 2013-11-19
  • 2019-06-23
  • 2016-04-18
  • 1970-01-01
  • 2014-05-30
  • 1970-01-01
  • 2020-03-30
  • 2016-07-26
相关资源
最近更新 更多