ngFor 没有完全更新 dom

ngFor does not update the dom fully

我在使用 ngFor 时遇到了一个奇怪的行为:

一般用法:我的后端存储了一个文本列表。用户可以显示此列表并获取由 ngFor 生成的列表,其中的值预设为列表内容。此外,他还可以编辑文本并将更新后的文本发送到后端。然后后端将更新整个列表并向所有客户端发送通知。如果其中一个客户端正在显示更新后的列表,它会再次获取列表,以便它是最新的。 (这种情况反正发生在小编身上,所以对小编没有什么特别的威胁)

也许我的方法不是最好的,但问题是不同的: 新列表异步到达并得到更新。问题是用于编辑的文本将被推送 "down"。当后端有正确的列表以及新获取的列表正确到达客户端时,列表未正确显示。它必须有一个 display/change 检测问题。

我尝试使用 "track by" 功能但没有成功。

最小工作示例:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<div *ngFor="let i of testList">
                <input type="text" [value]="i">
              </div>
  <button (click)="onClick()">Click</button>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'test-app';
  testList = ["one", "two", "three", "", ""];

  onClick()
  {
    setTimeout(()=>{
      this.testList = ["one", "two", "three", "four", ""];
    }, 2000)
  }
}

在第四个文本字段中输入内容,然后按下按钮。 2 秒后,您的文本应移至第 5 个字段。

Before Click

After Click and 2sec

Expected

提前致谢

这是 Angular 阴影 DOM 更新的行为。您可以这样更改代码:

setTimeout(()=>{
  this.testList = ["one", "two", "three", "four", null];
}, 2000)