创建自定义管道以使用角度谓词过滤值

时间:2017-05-12 13:01:13

标签: angular predicate arrow-functions angular-template angular-pipe

我想在角度4.x中创建一个自定义管道,它将谓词函数作为参数,以便从数组中过滤值。

以下是我的管道代码:[Snippet#1:mypipe.ts]

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(values: any[], predicate: (any) => boolean): any {
    return values.filter(predicate);
  }
}

以下是我在模板中使用它的方法:[Snippet#2:mycomponent.html]

<div *ngFor="let item of (items | filter:(x=>x.isValid))">

但在运行时,我收到此错误:[Snippet#3]

Error: Uncaught (in promise): Error: Template parse errors:
Parser Error: Bindings cannot contain assignments at column 44 in [let item of (items | filter:(x=>x.isValid))]

我通过在我的组件中创建一个isValid()函数并使用此函数作为我的过滤器的参数来解决这个问题:

[Snippet#4:mycomponent.ts]

isItemValid(item): boolean {
  return item.isValid;
}

[Snippet#5:mycomponent.html]

<div *ngFor="let item of (items | filter:isItemValid)">

但我真的不喜欢这个选项,因为我认为它的可读性低于使用箭头功能(你必须切换到component.ts文件以了解将在component.html中过滤的内容)。

是否有一个更好的解决方案看起来像片段#2?

1 个答案:

答案 0 :(得分:1)

没有更好的解决方案。 Angular的解析器不支持将这样的方法声明为任何绑定的一部分 - 可能是因为人们不在其模板中编写大型函数,因为控制器假设持有该逻辑。

我认为这个用例比大多数情况更接近灰色区域,但Angular在这方面足够自以为是他们不会让你尝试。

有关详细信息,请参阅此处: Angular 2 - Bindings cannot contain assignments

相关问题