angular 2:在不丢失数据绑定的情况下在管道中连接数组

angular 2: concat arrays in a pipe without loosing databinding

我有一个简单的管道:

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 中删除管道,我会收到预期的更改。

我想我对数据绑定的工作原理有一些误解。

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

如果您修改其中一个数组,Angular更改检测将看不到更改,因此不会调用管道。
Angular 更改检测仅检查对象标识,但不检查对象内容。

您可以使管道不纯,或者您可以在每次修改后创建管道的副本 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>

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

如果数组引用没有改变,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)

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