角度2:管道中的concat数组,不会丢失数据绑定

Dra*_*man 2 data-binding concat pipe angular

我有一个简单的管道:

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

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

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

我想我很想知道数据绑定是如何工作的.

感谢您提供有用的信息.

Gün*_*uer 5

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

您可以使管道不纯,或者您可以在每次修改Angular后创建管道的副本以查看新阵列.

@Pipe({ name: '...', pure: false})
Run Code Online (Sandbox Code Playgroud)

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

someMethod() {
  this.newItems.push(someNewItem);
  this.newItems = this.newItems.slice();
}
Run Code Online (Sandbox Code Playgroud)

修改后创建副本会导致角度变化检测以识别更改并调用管道.

另一种方法是使用伪参数;

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

这样,更改检测将检测参数的更改并调用管道.