【问题标题】:Incremental DOM doesn't work in nested ngFor增量 DOM 在嵌套的 ngFor 中不起作用
【发布时间】:2020-09-15 11:28:38
【问题描述】:

我设计了一个简单的对象数组来测试 Angular Incremental DOM。它在我向数组添加新值时起作用(DOM 仅在数组的最后一个位置更改),但是当我尝试更改数组中的值时,它会再次重新渲染整行,即使我只更改了一个数组中第一个对象中的项。

请参见下面的 gif。第一次闪烁是addRow() 第二次、第三次、第四次是changeAmount()

<button (click)="addRow()">Add row</button>
<button (click)="changeAmount()">Change 1st row amount</button>
<table>
    <tbody>
        <tr *ngFor="let row of matrix">
            <td *ngFor="let column of columns">{{row[column]}}</td>
        </tr>
    </tbody>
</table>
export class AppComponent {
  public columns = ["name", "value"];
  public matrix = [
    { name: "foo1", value: 1 },
    { name: "foo2", value: 2 },
    { name: "foo3", value: 3 },
    { name: "foo4", value: 4 }
  ];

  addRow(): void {
    const rand = this.randNumber(5, 50);
    this.matrix = [
      ...this.matrix,
      {
        name: "foo" + rand,
        value: rand
      }
    ];
  }

  changeAmount(): void {
    this.matrix = [
      ...this.matrix.map((v, k) => {
        if (k === 0) {
          return {
            ...v,
            value: this.randNumber(800, 3000)
          };
        }
        return v;
      })
    ];
  }

  private randNumber(min: number, max: number): number {
    return Math.floor(Math.random() * (max - min) + min);
  }
}

当我尝试将 trackBy 添加到 ngFor 时,它的行为相同(重新渲染整个 tr)。

当我点击 changeAmount 按钮时,只有 &lt;td&gt; 发生变化时,如何改进给定代码以实现结果。甚至可以在嵌套的*ngFor 中使用。 我可以删除 ChangeDtection.OnPush 并将函数修改为:

changeAmount(): void {
  this.matrix[0].value = this.randNumber(800, 3000);
}

但是当 ChangeDetection.OnPush 开启时我需要这个功能。

StackBlitz example

【问题讨论】:

    标签: angular


    【解决方案1】:

    只需在changeAmount2() 方法中添加这一行..

    this.matrix = [...this.matrix];
    

    基本上,您需要在 onPush 策略开启时更改 Object 的引用。所以你的方法是……

    changeAmount2(): void {
       this.matrix[0].value = this.randNumber(800, 3000);
       this.cdr.detectChanges();
       this.matrix = [...this.matrix];
    } 
    

    现在,changeDetection.onPush() 可以检测到属性的变化。

    【讨论】:

      猜你喜欢
      • 2017-01-11
      • 2019-12-03
      • 1970-01-01
      • 2017-09-04
      • 2019-03-20
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 2014-05-30
      相关资源
      最近更新 更多