【发布时间】: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 按钮时,只有 <td> 发生变化时,如何改进给定代码以实现结果。甚至可以在嵌套的*ngFor 中使用。
我可以删除 ChangeDtection.OnPush 并将函数修改为:
changeAmount(): void {
this.matrix[0].value = this.randNumber(800, 3000);
}
但是当 ChangeDetection.OnPush 开启时我需要这个功能。
【问题讨论】:
标签: angular