简体   繁体   English

如何使用Angular2传递有关如何在管道中进行过滤的元数据?

[英]How to pass meta data about how to filter in pipe using Angular2?

Consider the following 考虑以下

Here is my component 这是我的组件

 @Component({
  selector: 'myInput',
  pipes: [myPipe],
  template: 
  `
    <input [(ngModel)]="searchText" placeholder="name">
    <li *ngFor="#item of items | searchByTitle: searchText">
      <div>{{item.title}}</div>
    </li>
  `,
 })

Here is my pipe 这是我的烟斗

@Pipe({
    name: "searchByTitle"
})
export class myPipe {

    transform(value, args: any[]) {
        return value.filter(item => item.title.indexOf(args[0]) !== -1);
    }
}

As we can see from the above code we are filtering the list using user inputted searchText , the searchText is the filter criteria for the title. 从上面的代码中可以看出,我们正在使用用户输入的searchText过滤列表, searchText是标题的过滤条件。

However if I have the following data 但是,如果我有以下数据

items = [{'myTitle': 'title1'}, {'myTitle': 'title2'}]

it would not work, I can only pass in data that have the key title in it, is there a way I can pass in an arbitrary key to filter by? 它不起作用,我只能传递其中包含键title数据,有没有办法传递任意键作为筛选依据?

Such that I can do 这样我可以做

return value.filter(item => item[myArbiraryKey].indexOf(args[0]) !== -1);

You could provide several parameters to your pipe: 您可以为管道提供几个参数:

@Pipe({
  name: "searchByTitle"
})
export class myPipe {
  transform(value, args: any[]) {
    var field = args[0];
    return value.filter(item => item[field].indexOf(args[1]) !== -1);
  }
}

and use it this way: 并以这种方式使用它:

<li *ngFor="#item of items | searchByTitle:title:searchText">
  <div>{{item.title}}</div>
</li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM