【问题标题】:angular 2: concat arrays in a pipe without loosing databinding角度 2:管道中的 concat 数组而不会丢失数据绑定
【发布时间】:2017-10-07 23:29:07
【问题描述】:

我有一个简单的管道:

export class MergePipe implements PipeTransform {
transform(first: any[], second: any[], order: Boolean): any {
    return order ? first.concat(second):second.concat(first);
}

我在一个简单的按钮上使用它:<button *ngFor="let item of items | sort:suffix | filter:filterargs | merge:newItems:false"></button>

然后使用 newItems.push(values) 将一些值推送到 newItems 中,但没有任何反应。如果我从 *ngFor 中删除管道,我会收到预期的更改。

我想我对数据绑定的工作方式有误解。

感谢您提供任何有用的信息。

【问题讨论】:

  • 纯管道仅在更改pointer 时更新,例如您的first 更改为另一个数组,而不是可变的本身。您可以通过设置@Pipp({ pure: false }) 更改为不纯管道。你可以搜索管道文档。
  • 感谢您的回答。使用不纯的管道它可以正常工作,但现在并不真正了解它是如何工作的。

标签: angular data-binding pipe concat


【解决方案1】:

如果您修改其中一个数组,Angulars 更改检测将看不到更改,因此不会调用管道。
角度变化检测仅检查对象身份,而不检查对象内容。

您可以使管道不纯,或者您可以在每次修改后创建管道的副本,以便 Angular 看到一个新数组。

@Pipe({ name: '...', pure: false})

这可能会导致严重的性能问题,因为现在每次运行更改检测时都会调用管道。

someMethod() {
  this.newItems.push(someNewItem);
  this.newItems = this.newItems.slice();
}

修改后创建副本会导致 Angular 更改检测识别更改并调用管道。

还有一种方法是使用虚拟参数;

counter:int = 0;
someMethod() {
  this.newItems.push(someNewItem);
  this.counter++;
}
<button *ngFor="let item of items | sort:suffix | filter:filterargs | merge:newItems:false:counter"></button>

这种方式变化检测会检测到参数的变化并调用管道。

【讨论】:

  • 非常感谢,完美的答案,尤其是第二种解决方案是一个很好的解决方法。
【解决方案2】:

如果数组引用没有改变,Angular 似乎不知道重新评估该管道。

如果我们看看他们对管道的讨论:

You add the hero into the heroes array. The reference to the array hasn't changed. It's the same array. That's all Angular cares about. From its perspective, same array, no change, no display update.

https://angular.io/docs/ts/latest/guide/pipes.html

你应该把这段代码改为:

newItems = newItems.concat(values)

这将更新引用并导致重新评估管道。

【讨论】:

    猜你喜欢
    • 2018-10-24
    • 2011-02-12
    • 2017-10-18
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多