【问题标题】:Update Only changed Objects inside Array inside ngFor?更新仅在 ngFor 内的 Array 内更改了对象?
【发布时间】:2019-08-14 02:31:51
【问题描述】:

我每秒都有一个来自服务器的 JSON(对象数组)。我只想为数据更改且未更改的对象保持不变的对象更新 UI。我假设数据从服务器到达 2 次。

1st time:

[
  {} //Object1
  {} //Object2
  {} //Object3
]

2nd time:

 [
  {} //Object1.Changed
  {} //Object2.Unchanged
  {} //Object3.changed
 ]

我想在 UI 中显示所有 3 个对象,但我希望更改仅反映到 Object1 和 Object3,并且我不想TOUCH Object2,因为它没有更改。

有可能吗?

【问题讨论】:

  • 是的,有可能[需要思考],但您为什么要这样做?有什么特殊原因吗?

标签: angular ngfor


【解决方案1】:

为避免这种昂贵的操作,您可以自定义默认跟踪算法。通过向 NgForOf 提供 trackBy 选项。 trackBy 接受一个有两个参数的函数:index 和 item。如果给出了 trackBy,Angular 会根据函数的返回值跟踪变化。

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li>
    </ul>
    <button (click)="getItems()">Refresh items</button>
  `,
})
export class App {

  constructor() {
    this.collection = [{id: 1}, {id: 2}, {id: 3}];
  }

  getItems() {
    this.collection = this.getItemsFromServer();
  }

  getItemsFromServer() {
    return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
  }

  trackByFn(index, item) {
    return index; // or item.id
  }
}

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 2021-11-27
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多