如何使用 *ngFor 在同一个对象上迭代两次?

How do I use *ngFor to iterative twice on the same object?

我使用 Angular 集成器 *ngFor 来遍历我 HTML 中的一个对象。因为我迭代了两次,我在这两次迭代中遇到了问题,其中 [specID],我绑定到我的 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,但我似乎无法使用它。

我认为 scenario.timescenario.getSpectra() 是根据数组中的位置相关的。

那么你可以这样访问:

<div *ngFor="let spectra of scenario.getSpectra(); let i = index">
    <timeline [specId]="spectra.id" [ticks]="pos[i]"></timeline>
  </div>

您需要在组件 class 中准备一个组合列表,其中包含两个列表(timegetSpectra())的所有可能组合。然后在模板中只使用单循环。

将以下内容添加到您的组件中class

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>

更新了评论中建议的示例。