问题描述
我在ngFor中有一个组件"bar".我想用动画从以前的值开始将其宽度更新为新的宽度.
I have a component 'bar' inside ngFor. I want to update its width with animation starting from the previous value to new one.
html:
<div *ngFor="let station of stations" class="station">
<bar [perc]="station.perc" class="bar"></bar>
</div>
ParentComponent:
ParentComponent :
ngOnInit(){
setInterval(() => this.updateData(), 10000);
}
updateData(){
const url = 'http://....';
this.http.get(url)
.map(res => res.json())
.subscribe(data => {
this.stations = data;
});
}
BarComponent
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().
But on each updateData() it looks like ngFor recreates the dom and BarComponent is constructed again. So even if 'station.perc' is the same, ngOnChanges() is fired.
过渡从0开始重新启动,而不是从以前的值开始重新启动...
And the transition keeps on restarting from 0 instead of starting from the previous value...
我可能在这里遗漏了一个关键点,但是干净的解决方法是什么?
I probably miss a crucial point here but whats the clean workaround?
推荐答案
我想您应该使用trackBy
选项来自定义ngFor
指令的默认跟踪算法:
I guess you should use trackBy
option to customize the default tracking algorithm the ngFor
directive:
视图
<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:
or a bit better use unique id:
trackByFn(index, station) {
return station.id;
}
在此处查看有关轨道的更多详细信息:
See more details about the trackBy here:
希望 柱塞示例 也会为您提供帮助.
Hope Plunker Example will also help you.
这篇关于Angular 2-使用ngFor,是否可以在不重建dom的情况下更新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!