我使用 Angular 集成器 *ngFor 来迭代 HTML 中的对象。由于我迭代了两次,因此这次两次迭代出现了问题,其中 [specID]
(我绑定(bind)到 TimelineComponent 的输入)在 2 个循环中显示。
<div *ngFor="let pos of scenario.time">
<div *ngFor="let spectra of scenario.getSpectra()">
<timeline [specId]="spectra.id" [ticks]="[pos]"></timeline>
</div>
</div>
这是我的场景类型(我不确定这是否相关):
import {spectra} from "../data";
import {Spectra} from "./spectra";
export class Scenario {
id: string;
time: number[];
spectra: string[];
constructor(id: string, time: number[],
spectra: string[],
) {
this.spectra = spectra;
this.id = id;
this.time = time;
}
getSpectra(): Spectra[] {
return spectra.filter(spectrum => this.spectra.includes(spectrum.id))
}
}
还有我的数组、场景和光谱:
export const scenarios: Scenario[] = [
new Scenario( "1", [0.0, 0.14, 1], ["1", "2", "3"]),
new Scenario( "2", [0.0, 0.33, 1], ["1", "2", "3"])
];
export const spectra: Spectra[] = [
new Spectra("1", [0.2, 0.2, 0.6], ["1", "2", "3"]),
new Spectra("2", [0.33, 0.33, 0.33], ["1", "2", "3"]),
new Spectra("3", [0.4, 0.4, 0.2], ["1", "2", "3"])
];
解决这个问题的最佳方法是什么?我尝试在同一个 div 中使用我的两个 *ngFor
但似乎我无法使用它。
最佳答案
您需要在组件类中准备一个组合列表,其中包含两个列表( time
和 getSpectra()
)的所有可能组合。然后在模板中仅使用单个循环。
将以下内容添加到您的组件类
export class SomeComp implements OnInit {
...
someList: any[];
...
ngOnInit(): void {
this.someList = [];
for(let t of this.scenario.time)
for(let s of this.scenario.getSpectra())
this.someList.push({pos: t, spectraId: s});
}
...
}
并像这样更改模板:
<div *ngFor="let item of someList">
<timeline [specId]="item.spectraId" [ticks]="[item.pos]"></timeline>
</div>
按照评论中的建议更新了示例。
关于angular - 如何使用 *ngFor 对同一对象迭代两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57962179/