To avoid the expensive operations, we can help Angular to track which items added or removed i.e. customize the default tracking algorithm by providing a trackBy option to NgForOf.

So you can provide your custom trackBy function that will return unique identifier for each iterated item.
For example, some key value of the item. If this key value matches the previous one, then Angular won’t detect changes.

trackBy takes a function that has index and item args.

  selector: 'my-app',
  template: `
      <li *ngFor="let item of items; trackBy: trackByFn">{{}}</li>
export class AppComponent { 
  trackByFn(index, item) {

If trackBy is given, Angular tracks changes by the return value of the function.

Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create/destroy only changed items.

继续阅读 30秒学会 Angular 片段 – trackBy in for loops