如何通过数组作为Angular2精氨酸在管 [英] How to pass array as arg in Pipe in Angular2
问题描述
我创建了一个烟斗的目的是根据标签列表来过滤列表。
I have created a Pipe which purpose is to filter a list depending on a list of tags.
@Pipe({
name: "tagfilter"
})
export class TagFilterPipe implements PipeTransform {
transform(items: Event[], args: any[]) :any {
if (args.length === 0) {
return items;
}
return _.filter(items, (item: any) => {
return (_.intersection(item.tags, args[0]).length > 0)
});
}
}
我然后使用它是这样的:
I am then using it like this :
<tbody class="myline" *ngFor="#event of chapter.events | tagfilter:selectedTags" [event]="event">
不过,selectedTags是一个字符串数组,如果我添加或从该数组中删除条目,它不会触发过滤器,因此,不会被过滤掉我的名单:/
However, "selectedTags" is an array of strings and if I add or remove entries from this array, it does not trigger the filter and so, my list is not filtered :/
推荐答案
我认为这是改变检测Angular2是如何工作的。我的意思是对象中的更新不会引起变化的检测,但如果你更新整个引用,它的作用。
I think that it's how change detection works in Angular2. I mean updates within objects don't trigger change detection but if you update the whole reference, it does.
要重新评估的管道,你需要更换阵列一个新的:
To reevaluate the pipe, you need to replace the array with a new one:
@Component({
selector: 'my-app',
template: `
<div>
<span *ngFor="#l of (list | sort:excluded)">{{l}}</span>
</div>
<div (click)="updateArgs()">Update args</div>
`,
pipes: [ SortPipe ]
})
export class AppComponent {
constructor() {
this.list = [ 'n', 'g', 'a', 'u', 'r', 'l' ];
}
updateArgs(array) {
this.excluded = [ 'n', 'g' ];
}
}
在我的样本,在执行时 updateArgs
的变换
管道的方法再次被调用。
In my sample, when executing updateArgs
, the transform
method of the pipe is called again.
下面是一个plunkr: https://plnkr.co/edit/GWcEOeY0koXZ5vroRntV? p = preVIEW 。
Here is a plunkr: https://plnkr.co/edit/GWcEOeY0koXZ5vroRntV?p=preview.
希望它可以帮助你,
蒂埃里
Hope it helps you, Thierry
这篇关于如何通过数组作为Angular2精氨酸在管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!