我正在尝试使用for循环生成3个Google图表。每个Google图表都应在饼图中显示不同的数据。
为了实现这一目标,我将Google图表嵌入了儿童组件中,该组件从父母那里获取一些输入变量并呈现图表。
我注意到所有3个图表都仅显示最后一个数据,而不是显示每组数据的不同图表。我在这里做错了什么?
Stackblitz
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]];
}
}
根据您的app.component.ts
,您正在调用具有不同值的相同函数drawChart(index)
替换相同的值。
因此,唯一的最后迭代存在。看一下这个Stackblitz
希望这会有所帮助:(
而不是更新相同的变量,您可以将属性推到results
数组并在HTML中使用其属性
<div *ngFor="let result of results; index as i;">
<app-google-chart #chart{{i}}
[title]="result.title"
[type]="result.type"
[data]="result.data"
[columnNames]="columnNames"
[options]="options"
[width]="width"
[height]="height">
</app-google-chart>
</div>
export class AppComponent implements OnInit {
// or a different set of data to be looped through in OnInit
dataLength = 3;
// data to be passed to children component
results = [];
ngOnInit() {
for(let i = 0;i < dataLength; i++) {
this.results.push(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;
}
// instead of this
this.title = "Chart" + index;
this.type = "PieChart";
this.data = [['Pass', passed], ['Fail', failed]];
return {
title: 'Chart' + index,
type: 'PieChart',
data: [['Pass', passed], ['Fail', failed]]
};
}
}