角度2:管道中的concat数组,而不会丢失数据绑定 [英] angular 2: concat arrays in a pipe without loosing databinding

查看:150
本文介绍了角度2:管道中的concat数组,而不会丢失数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的管道:

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>.

Which I'm using on a simple button: <button *ngFor="let item of items | sort:suffix | filter:filterargs | merge:newItems:false"></button>.

然后使用newItems.push(values)将一些值推送到newItems中,但是什么也没有发生.如果我从* ngFor中删除管道,则会收到预期的更改.

And then push some values into the newItems with newItems.push(values) but nothing happens. If I remove the pipe from *ngFor, I receive the expected changes.

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

I think I missunderstand something on how the databinding is working.

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

Thanks for any helpful information.

推荐答案

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

If you modify one of the arrays, Angulars change detection won't see the change and therefore won't call the pipes.
Angular change detection only checks object identity, but not object content.

您可以使管道不纯,也可以在每次修改后为Angular创建管道副本以查看新数组.

You can make the pipe impure, or you can create a copy of the pipe after each modification for Angular to see a new array.

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

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

This can cause severe performance issues, because now the pipe is called every time change detection is run.

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

修改后创建副本会使Angular更改检测功能识别出更改并调用管道.

Creating a copy after modification causes Angular change detection to recognize the change and call the pipes.

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

Yet another way is to use a dummy parameter;

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>

通过这种方式,更改检测将检测到参数的更改并调用管道.

This way change detection will detect the change of a parameter and call the pipes.

这篇关于角度2:管道中的concat数组,而不会丢失数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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