Angular 2-使用ngFor,是否可以在不重建dom的情况下更新值? [英] Angular 2 - with ngFor, is it possible to update values without rebuilding the dom?

查看:273
本文介绍了Angular 2-使用ngFor,是否可以在不重建dom的情况下更新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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的情况下更新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆