首页 > 解决方案 > 使用angular和chartjs在一页上显示多个图表

问题描述

我正在尝试使用 *ngFor 循环在单个页面上显示多个图表,但我很难让它显示其中的任何一个。

我尝试使用子组件无济于事,不确定这甚至是要走的路。

import { Component, OnInit } from '@angular/core';
import { _ } from 'underscore';
import { Chart } from 'chart.js';

@Component({
  selector: 'app-sports-cards',
  templateUrl: './sports-cards.component.html',
  styleUrls: ['./sports-cards.component.scss']
})

export class SportsCardsComponent implements OnInit {

  chart: [];

  games = [
    {
      id: '1',
      homeTeam: 'Bretts team',
      awayTeam: 'Another team',
      gameTime: 'March 15, 1989'
    },
    {
      id: '2',
      homeTeam: 'Andys team',
      awayTeam: 'Another team',
      gameTime: 'March 15, 1989'
    },
    {
      id: '3',
      homeTeam: 'Missys team',
      awayTeam: 'Another team',
      gameTime: 'March 15, 1989'
    },
    {
      id: '4',
      homeTeam: 'Jons team',
      awayTeam: 'Another team',
      gameTime: 'March 15, 1989'
    },
  ];

  constructor() { }

  ngOnInit() {
    _.each(this.games, (game) => {
      this.chart = new Chart(game.id, {
        type: 'doughnut',
      data: {
        labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
        datasets: [
          {
            label: "Population (millions)",
            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
            data: [2478,5267,734,784,433]
          }
        ]
      },
      options: {
        title: {
          display: true,
          text: 'Predicted world population (millions) in 2050'
        }
      }
      });
    });
  }
}

这是我的 HTML

<div class="col-lg-9 float-right">
  <div class="row">
    <div class="col-lg-6 card-background"
      *ngFor="let game of games"
    >
      <div class="card-surround shadow-sm">
        <div>
            <h2>{{game.homeTeam}}</h2>
            <h2>{{game.awayTeam}}</h2>
            <canvas id="{{game.id}}">{{ chart }}</canvas>
            <hr>
            <p>{{game.gameTime}}</p>
        </div>
      </div>
  </div>
</div>

我收到错误:无法创建图表:无法从给定项目获取上下文

标签: angularchart.js

解决方案


推荐阅读