Search code examples
angularangular2-templatengforangular2-changedetection

How to reuse the elements of ngFor even if the list reference changes?


I have an Angular 2 component that uses *ngFor to render a nested array of numbers.

@Component({
  selector: 'app',
  template: `
    <div *ngFor="let row in data">
      <div *ngFor="let curve in row">
        <chart [data]="curve">
      </div>
    </div>
  `,
  directives: [Chart],
})
export default class App {
  data: number[][][];
}

When I change data, Angular replaces the <chart> elements, even if the new array has the same dimensions. I'd like it only to update the properties of the charts but keep the elements (so that I can animate the data changes).

It's understandable that Angular replaces the elements since the new array is a new object reference. But how can I circumvent this?


Solution

  • Using ngForTrackBy should help you here.

    The following function should update the element properties whilst keeping the elements in the DOM.

    trackByIndex(index: number, data: any) { return index; }