【发布时间】:2019-07-03 20:07:11
【问题描述】:
我正在尝试使用 for 循环生成 3 个 Google 图表。每个 Google 图表都应在饼图中显示不同的数据。
为此,我将 Google Chart 嵌入到一个子组件中,该子组件从父组件获取一些输入变量并呈现图表。
我注意到所有 3 个图表都只显示最后传递的数据,而不是为每组数据显示不同的图表。我在这里做错了什么?
app.component.html
<div *ngFor="let result of results; index as i;">
<app-google-chart #chart{{i}}
[title]="title"
[type]="type"
[data]="data"
[columnNames]="columnNames"
[options]="options"
[width]="width"
[height]="height">
</app-google-chart>
</div>
app.component.ts
export class AppComponent implements OnInit {
constructor() {}
results = ["1","2","3"];
title;
type;
data;
columnNames;
options;
width;
height;
ngOnInit() {
for(let i=0;i<this.results.length;i++)
{
this.drawChart(i);
}
}
drawChart(index:any) {
var passed;
var failed;
if(index == 0)
{
passed=50;
failed=50;
}
else if(index == 1)
{
passed=20;
failed=30;
}
else if(index == 2)
{
passed=40;
failed=60;
}
this.title = "Chart" + index;
this.type = "PieChart";
this.data = [['Pass', passed], ['Fail', failed]];
}
}
【问题讨论】:
-
[data]="data":您将相同的AppComponent.data传递给每个图表。您的 TypeScript 代码没有多大意义:您在循环的每次迭代中都覆盖了相同的实例变量。如果你想要组件中的三个不同的数据,你需要一个由 3 个元素组成的数组。 -
hmm.. 我不确定如何修复我的打字稿代码以将唯一值传递给子组件。
标签: angular