我似乎无法让我的chart.js在循环数组中的页面上显示多个图表。
我尝试过使用view child,但是这是它自己的问题。
这是我的使用伪数据的TS文件:
import { Component, OnInit, AfterContentInit, AfterViewChecked, AfterViewInit } 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, i) => {
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>
这是我当前遇到的错误。
Chart.js:8459无法创建图表:无法从给定项目获取上下文
答案 0 :(得分:0)
好一阵子尝试不同的方法后,这似乎对我有用。
ngAfterViewInit() {
this.loadCharts();
}
loadCharts() {
_.each(this.games, (game, i) => {
this.chart = new Chart(game.id, {
type: 'doughnut',
data: {
labels: [game.homeTeam, game.awayTeam],
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'
}
}
});
});
}
基本上,它正在等待视图初始化,然后将图表分配给我创建的卡片。