ngFor中的索引不是唯一的

问题描述 投票:0回答:1

你好,我有一个基本的togglehide功能,用于显示和隐藏用户点击的内容。在第一次点击时,它从API加载数据。但是有时索引是相同的,所以打开的是2个元素而不是一个。

简化后的html

<div *ngFor="let children of day.filteredChildren$ | async; let j = index">
<div class="child-dayreport" *ngIf="children.hasDayreport == 1">
                    <button class="btn-show-report"
                      (click)="toggleReportVisibility(children.id, selectedDateTitle, j)">{{childrenAll[j].reportExpanded ? 'Verstecke Tagesrapport' : 'Zeige Tagesrapport'}}</button>
                  </div>
                  <div class="child-dayreport" *ngIf="children.hasDayreport > 1">
                    <button class="btn-show-report"
                      (click)="toggleReportVisibility(children.id, selectedDateTitle, j)">{{childrenAll[j].reportExpanded ? 'Verstecke Tagesrapport' : 'Zeige Tagesrapport'}}</button>
                  </div>
<div>

点击处理程序

toggleReportVisibility(id, date, index) {
    console.log('toggleReportVisibility', id, date, index)
    this.childrenAll[index].reportExpanded = !this.childrenAll[index].reportExpanded;

    const currentChild: any = this.childrenAll.filter(child => child.id === id);
    if (currentChild[0].reports.length === 0 && currentChild[0].hasDayreport !== 0) {
      this.getChildrenDailyReport(id, date)
        .then(() => this.childrenAll[index].reports = this.report)

    }
  }

@EDIT 我试着添加TrackBy这样的功能,但是没有成功。

<div *ngFor="let children of day.filteredChildren$ | async; index as j; trackBy: trackByFn">
trackByFn(i: number) {
    return i;
}
angular ionic4
1个回答
0
投票

我没有精确地检查HTML文件,它是巨大的... 而且这个循环是另一个循环的一部分,所以*ngFor索引是正确的。创建独立的计数器 children.counter 变量,它总是唯一的。

<button class="btn-show-report"
(click)="toggleReportVisibility(children.id, selectedDateTitle, children.counter)">{{childrenAll[children.counter].reportExpanded ? 'Verstecke Tagesrapport' : 'Zeige Tagesrapport'}}</button>
© www.soinside.com 2019 - 2024. All rights reserved.