How to reuse ngFor elements even if the link to the list 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 the data , Angular replaces the <chart> elements, even if the new array is the same size. I would only like to update the properties of the diagrams, but save the elements (so that I can animate the changes in the data).

It is understood that Angular replaces elements, since the new array is a new reference to the object. But how can I get around this?

+7
angular angular2-template angular2-changedetection ngfor
source share
2 answers

Using ngForTrackBy should help you here.

The following function should update the properties of an element when saving elements in the DOM.

 trackByIndex(index: number, data: any) { return index; } 
+5
source share

Working plunker

Flat data structure

You can separate the metadata from your diagrams (name, identifier, etc.) from the actual data points that will change and animate.

The *ngFor will use an array of metadata, and each chart component will have @Input() , which will be retrieved from a separate data point object.

 // Metadata this.charts = [ { id: 1, title: 'Chart Title 1', }, { id: 2, title: 'Chart Title 2', } ]; // Data Points this.chartData = { 1: [87, 95, 121, 20, 60, 131, 10, 139, 128, 99], 2: [56, 107, 107, 144, 43, 7, 67, 35, 141, 62] } 

Template

 <div *ngFor="let chart of charts"> <app-chart [inputMeta]="chart" [inputData]="chartData[chart.id]"></app-chart> </div> 

Then, in the chart component, you can use the ngOnChanges() life cycle binding to update the chart when updating your data points.

+2
source share

All Articles