Angular 2 - with ngFor, is it possible to update values ​​without restoring dom?

I have a component bar inside ngFor. I want to update its width with animation, from the previous value to the new one.

html:

<div *ngFor="let station of stations" class="station"> <bar [perc]="station.perc" class="bar"></bar> </div> 

ParentComponent:

 ngOnInit(){ setInterval(() => this.updateData(), 10000); } updateData(){ const url = 'http://....'; this.http.get(url) .map(res => res.json()) .subscribe(data => { this.stations = data; }); } 

Barcomponent

 export class BarComponent { @Input() perc; constructor(private element: ElementRef){} ngOnChanges(changes: any): void { let perc = changes.perc.currentValue; TweenMax.to(this.element.nativeElement, 1, { width: perc + '%' }); } } 

But on each updateData (), it looks like ngFor to recreate the dom and the BarComponent is created again. Therefore, even if "station.perc" matches, ngOnChanges () is triggered.

And the transition continues restarting from 0 instead of starting from the previous value ...

I probably missed an important point here, but what is a workaround?

+6
source share
1 answer

I think you should use the trackBy option to configure the default tracking algorithm of the ngFor directive:

view

 <div *ngFor="let station of stations; let i = index; trackBy: trackByFn" class="station"> <bar [perc]="station.perc" class="bar"></bar> </div> 

component

 trackByFn(index, item) { return index; } 

or a little better to use a unique identifier:

 trackByFn(index, station) { return station.id; } 

Read more about trackBy here:

Hope An example plunger will also help you.

+15
source

All Articles