我使用了Angular integrator *ngFor来迭代HTML中的对象。因为我迭代了两次,所以我在这个双重迭代中遇到了一个问题,其中绑定到我的TimelineComponent的输入[specID]显示在两个循环中。
<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,但似乎无法使用。
发布于 2019-09-17 02:29:11
您需要在component类中准备一个组合列表,其中包含两个列表( 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>根据评论中的建议更新了示例。
发布于 2019-09-17 02:09:34
我相信scenario.time和scenario.getSpectra()是通过数组中的位置相关的。
然后,您可以像这样访问:
<div *ngFor="let spectra of scenario.getSpectra(); let i = index">
<timeline [specId]="spectra.id" [ticks]="pos[i]"></timeline>
</div>https://stackoverflow.com/questions/57962179
复制相似问题