使用angular和chartjs在一页上显示多个图表

时间:2019-06-05 21:51:28

标签: angular chart.js

我正在尝试使用* 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>

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

0 个答案:

没有答案