嵌套ngFor循环中索​​引的多次迭代

时间:2018-04-20 16:32:20

标签: javascript angular typescript ngfor

我对ngFor循环中的迭代项使用trackByIndex函数:

trackByIndex(index: number, obj: any): any {
  return index;
}

以下是我的代码如何使用它的简短示例:

<div *ngFor="let comment of comments; let i = index; trackBy: trackByIndex">
  {{ i, comment.text }}
  <div *ngFor="let answer of comment.answers; let j = index; trackBy: trackByIndex">{{ j, answer.text }}</div>
</div>

但是当我的页面上有2个comment个项目时,我会在每个评论中都有相同的迭代答案:

"comment 1": {
    "answer 1",
    "answer 2"
},
"comment 2": {
    "answer 1", // should be answer 3
    "answer 2" // should be answer 4
}

我怎样才能解决这个问题?非常感谢任何提示。

1 个答案:

答案 0 :(得分:0)

我想,你错过了ngFor

的绑定

尝试使用

<div *ngFor="let comment of comments; let i = index; trackBy: trackByIndex">
  {{ i, comment.text }}
  <div *ngFor="let answer of comment.answers; let j = index; trackBy: trackByIndex">{{ j, answer.text }}</div>
</div>