我在ngFor中有一个组件’bar’.我想用从前一个值到新值的动画更新其宽度.
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 + '%' }); } }
但是在每个updateData()上,它看起来像ngFor重新创建dom并再次构造BarComponent.因此,即使’station.perc’相同,也会触发ngOnChanges().
并且转换从0开始重新开始,而不是从之前的值开始…
我可能错过了一个关键点,但是干净的解决方法是什么?
我想你应该使用trackBy选项来定制ngFor指令的默认跟踪算法:
原文链接:https://www.f2er.com/angularjs/143228.html视图
<div *ngFor="let station of stations; let i = index; trackBy: trackByFn" class="station"> <bar [perc]="station.perc" class="bar"></bar> </div>
零件
trackByFn(index,item) { return index; }
或者更好地使用唯一ID:
trackByFn(index,station) { return station.id; }
在这里查看有关trackBy的更多详细信息:
> https://angular.io/guide/template-syntax#ngfor-with-trackby
希望Plunker Example也会帮到你.