Asridh Kumar
Asridh Kumar

Reputation: 525

Update Only changed Objects inside Array inside ngFor?

I have a JSON(Array of Objects) coming from server for each second.I would like to update UI only for the objects whose data changes and unchanged object remain as same before.I am supposing data arrived 2 times from server.

1st time:

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

2nd time:

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

I want to display all 3 objects in UI but I want changes to be reflected to only Object1 and Object3 and I do not want to TOUCH Object2 as it is not changed.

Is it Possible ?

Upvotes: 4

Views: 1768

Answers (1)

Ivanes
Ivanes

Reputation: 533

To avoid this expensive operation, you can customize the default tracking algorithm. by supplying the trackBy option to NgForOf. trackBy takes a function that has two arguments: index and item. If trackBy is given, Angular tracks changes by the return value of the function.

@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
  }
}

Upvotes: 2

Related Questions