在过滤管道上使用多个字段| Angular 4

时间:2017-09-28 10:01:12

标签: javascript angular typescript

我想知道如何使用Pipe来使用多个输入字段来过滤json对象,到目前为止我的代码只有一个字段按名称过滤:

TS

members = [
    {name:'Carl', country:"Brazil"},
    {name:'John', country:"United States"},
    {name:'Madhu', country:"India"}
  ]

PIPE.TS

  transform(members: any, term: any): any {
//check if search term is undefined
if (term === undefined) return members;

//return updated members array
return members.filter(function(member){
  return member.name.toLowerCase().includes(term.toLowerCase());
})
  }

HTML

<input type="text" [(ngModel)]="term" name="any"/>

          <li *ngFor="let member of members | filter:term">

              <h3>{{member.name}}</h3>
              <span>{{member.country}}</span>

          </li>

我想添加一个额外的输入字段来搜索国家/地区。

编辑:

它使用以下代码:

TS COMPONENT

 fields: any  = { name: "", country: "" };
  filters: any = { name: "", country: "" };

  updateFilters(): void {
      this.filters = Object.assign({}, this.fields);
      console.log(this.filters);
  }

HTML

<input type="text" name="any" [(ngModel)] = "fields.name" (ngModelChange)="updateFilters()"/>
          <input type="text" name="anyy" [(ngModel)] = "fields.country" (ngModelChange)="updateFilters()"/>

<li *ngFor="let member of members | filter: filters">
            <div style="border-bottom: 1px solid; border-color:rgba(0,0,0,0.3);margin-bottom:15px">
              <h3>{{member.name}}</h3>
              <span>{{member.country}}</span>
            </div>
          </li>

PIPE.TS

  transform(members: any, filters: any): any {
    return members.filter(item => {
    return (item.name.toLowerCase().indexOf(filters.name.toLowerCase()) >= 0 && item.country.toLowerCase().indexOf(filters.country.toLowerCase()) >= 0);

    });
  }

1 个答案:

答案 0 :(得分:2)

您可以传递对象而不是多个字段:

<li *ngFor="let member of members | filter: filters">

在您的组件类中:

filters: any = { name: "ex", country: "a country" };

更新:

<input type="text" [(ngModel)] = "fields.name" (ngModelChange)="updateFilters()"/>
<input type="text" [(ngModel)] = "fields.country" (ngModelChange)="updateFilters()"/>

在您的组件中:

fields: any  = { name: "", country: "" };
filters: any = { name: "", country: "" };

updateFilters(): void {
    this.filters = Object.assign({}, this.fields);
}