我对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
}
我怎样才能解决这个问题?非常感谢任何提示。
答案 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>