如何通过手动键入数字并使用angular2过滤来过滤内容

时间:2018-03-22 11:39:39

标签: javascript angular typescript

我有4个字段来过滤表格内容。如果我在过滤器部分中放置2个值它可以工作,如果我再添加一个字段,即使一个工作也没有。任何人都可以帮我根据电子邮件和电话号码过滤内容。

enter image description here HTML: 使用过滤器数据的代码的上半部分:

<ng-select [options]="name" [(ngModel)]="filter.name"></ng-select>
      <ng-select [options]="email" [(ngModel)]="filter.email"></ng-select>
      <input type="number" onKeyPress="if(this.value.length==10) return false;" class="form-textbox input-text" [(ngModel)]="filter.phone_number">
      <ng-select [options]="pinAddress" [(ngModel)]="filter.address"></ng-select>

用于过滤表格的管道:

<tbody>
          <tr *ngFor="let pin of pins | pinfilter:filter">
            <td>{{pin.name}}</td>
            <td>{{pin.description}}</td>
            <td>{{pin.address}}</td>
            <td>{{pin.website}}</td>
            <td>{{pin.phone_number}}</td>
            <td>{{pin.email}}</td>
            <td>{{pin.comments}}</td>
          </tr>
        </tbody>

TS:

filter.pipe.ts:
/* Tutorial filter to write filter functions for Tutorial*/
import { Pipe, PipeTransform } from '@angular/core';

export class NewPin { 
  public _id:number;
  public user_id:number;
  public name:string;  
  public address:string;
  public phone_number:string;
  public email:string;
  public comments:boolean;
}

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

export class PinPipe implements PipeTransform { 
  transform(items: NewPin[], filter: NewPin): NewPin[] { 
    if (!items || (!filter.name && !filter.address)) { 
      return items; 
    } 
      return items.filter((item: NewPin) => this.applyFilter(item, filter)); 
  } 

  applyFilter(user: NewPin, filter: NewPin): boolean {
    console.log(filter);
    if (filter.name && filter.address) { 
      if (filter.name == user.name && filter.address == user.address) { 
        return true 
      } else { 
        return false 
      } 
    } else if (filter.name) { 
        if (filter.name == user.name) { 
          return true 
    } else { 
        return false 
      }  
    } else if (filter.address) { 
      if (filter.address == user.address) { 
        return true 
      } else { 
        return false 
      } 
    } else { 
      return true 
    } 
  } 
}

component.ts:

public filter: NewPin = new NewPin();

1 个答案:

答案 0 :(得分:1)

您需要更改applyFilter函数,以便根据要过滤的数据检查所有过滤器属性。

我还建议让它在结构上更简单一些,如下所示:

  applyFilter(user: NewPin, filter: NewPin): boolean {
    console.log(filter);
    // check all the filters
    if (filter.name && filter.name != user.name) { 
        return false; 
    } 
    if (filter.address && filter.address != user.address) { 
        return false 
    }  
    if (filter.email && filter.email != user.email) { 
        return false; 
    }  
    if (filter.phone_number && filter.phone_number != user.phone_number) { 
        return false;
    }  
    // if the user passes all the filters, show it
    return true; 
  }