如何在带有角度2滤波器的表格中对多列应用滤波器

时间:2016-12-22 10:21:36

标签: angular filter

我在当前项目中使用角度2。我正在尝试在我的表中应用多个过滤器选项。您可以参考以下代码。

在HTML模板中:

<table class="table table-condensed table-responsive">
    <thead>
        <tr>
            <td></td>
            <td *ngFor="let key of headers">{{key}}</td>
        </tr>
        <tr>
            <td></td>
            <td *ngFor="let key of headers; let i=index">
                <input type='text' id="{{key}}"  (keyup)="filterUser(key)" placeholder="Search User By {{key}}"/>
            </td>
        </tr>
    </thead>
    <tbody *ngFor="let user of alluser | userFilter : columnName : listFilter " #someVar>            
        <tr>
            <td><input type="checkbox" class="checkbox" value="{{user.Id}}" (change)="getSelectedUser()" [(ngModel)]="user.IsSelected" /></td>
            <td>{{user.UserName}}</td>
            <td>{{user.FirstName | uppercase}}</td>
            <td>{{user.LastName}}</td>
            <td><button type="button" class="btn btn-primary" (click)="editModal.Open(user)">Edit</button></td>
            <td><button class="btn btn-primary" (click)='deletemodal.open()'>Delete</button></td>
            <td></td>
        </tr>
    </tbody>
</table>

在Temple Templete中:

export class UserFilterPipe implements PipeTransform {
   transform(value: User[], field: string, args: string): User[]{
      let filter: string = args ? args.toLocaleLowerCase() : null;
      return filter ? value.filter((user: User) =>
          user[field].toLocaleLowerCase().indexOf(filter) != -1) : value;
   }
}

在组件中:

 filterUser(key) {
    debugger;
    this.columnName = key;
    var v1 = document.getElementById(key).value;
     this.listFilter = v1;

}

2 个答案:

答案 0 :(得分:2)

这可能有所帮助,可以过滤所有列上的任何表:

@Pipe({
name: 'tableFilter',
pure: false
})
export class TableFilterPipe implements PipeTransform {
keys = [];
transform(items: any, args: string): any {

if (items != null && items.length > 0) {
  let ans = [];

  if (this.keys.length == 0) {
    this.keys = Object.keys(items[0]);
  }

  for (let i of items) {
    for (let k of this.keys) {
      if (i[k].toString().match('^.*' + args +'.*$')) {
        ans.push(i);
        break;
      }
    }
  }
  return ans;
}
}

答案 1 :(得分:0)

Pipe的{​​{1}}语法是这样的:

transform

因此,在您的情况下,transform(__input__, __arg1__, __arg2__, ... __argn__) 应如下所示:

Pipe