首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在同一个对象上使用*ngFor迭代两次?

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

Stack Overflow用户
提问于 2019-09-17 02:01:18
回答 2查看 632关注 0票数 2

我使用了Angular integrator *ngFor来迭代HTML中的对象。因为我迭代了两次,所以我在这个双重迭代中遇到了一个问题,其中绑定到我的TimelineComponent的输入[specID]显示在两个循环中。

代码语言:javascript
复制
<div *ngFor="let pos of scenario.time">
  <div *ngFor="let spectra of scenario.getSpectra()">
    <timeline [specId]="spectra.id" [ticks]="[pos]"></timeline>
  </div>
</div>

以下是我的场景类型(我不确定这是否相关):

代码语言:javascript
复制
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))
  }
}

和我的两个数组,场景和频谱:

代码语言:javascript
复制
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,但似乎无法使用。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-17 02:29:11

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

将以下内容添加到组件类中

代码语言:javascript
复制
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});
    }
    ...
}

并按如下方式更改模板:

代码语言:javascript
复制
<div *ngFor="let item of someList">
    <timeline [specId]="item.spectraId" [ticks]="[item.pos]"></timeline>
</div>

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

票数 3
EN

Stack Overflow用户

发布于 2019-09-17 02:09:34

我相信scenario.timescenario.getSpectra()是通过数组中的位置相关的。

然后,您可以像这样访问:

代码语言:javascript
复制
<div *ngFor="let spectra of scenario.getSpectra(); let i = index">
    <timeline [specId]="spectra.id" [ticks]="pos[i]"></timeline>
  </div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57962179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档