如何使用ngx-datatable

时间:2018-08-02 14:59:56

标签: angular ngx-datatable

我正在使用此https://github.com/swimlane/ngx-datatable/blob/master/demo/basic/filter.component.ts来帮助我在表格中创建搜索。

我的目标是创建一个高级搜索:按性别和姓名值进行过滤

  rows = [
{ name: 'Austin', gender: 'Male', company: 'Swimlane' },
{ name: 'Dany', gender: 'Male', company: 'KFC' },
{ name: 'Molly', gender: 'Female', company: 'Burger King' },
];
columns = [
{ prop: 'name' },
{ name: 'Gender' },
{ name: 'Company' }
];

@ViewChild(DatatableComponent) table: DatatableComponent;

temp=[]

constructor() {
    this.temp = this.rows;
}

updateFilter(event) {
    const val = event.target.value.toLowerCase();

    const temp = this.temp.filter(function (d) {
        return d.name.toLowerCase().indexOf(val) !== -1 || !val;
    });

    this.rows = temp;
 }

 updateFilter1(event) {
  const val = event.target.value.toLowerCase();

  const temp = this.temp.filter(function (d) {
      return d.gender.toLowerCase().indexOf(val) !== -1 || !val;
  });
  this.rows = temp;
}

我只是复制搜索内容,创建了第二个按性别过滤的函数。但是,这两种搜索都是分开进行的(消除了另一种的限制),我不知道如何解决。

在这里您可以找到我的html

<input
    type='text'
    style='padding:8px;margin:15px auto;width:30%;'
    placeholder='Type to filter the name column...'
    (keyup)='filterByName($event)'
  />
  <input
    type='text'
    style='padding:8px;margin:15px auto;width:30%;'
    placeholder='Type to filter the name column...'
    (keyup)='filterByGender($event)'
  />
  <ngx-datatable
    #table
    class='material'
    [columns]="columns"
    [columnMode]="'force'"
    [headerHeight]="50"
    [footerHeight]="50"
    [rowHeight]="'auto'"
    [limit]="10"
    [rows]='rows'>
  </ngx-datatable>

1 个答案:

答案 0 :(得分:2)

... // other vars you already have
previousNameFilter = ''
previousGenderFilter = ''

filterByName(event) {
  const filter = event.target.value
  this.previousNameFilter = filter
  this.temp = this.filterRows(filter, this.previousGenderFilter)
}

filterByGender(event) {
  const filter = event.target.value
  this.previousGenderFilter = filter
  this.temp = this.filterRows(this.previousNameFilter, filter)
}


filterRows(nameFilter, genderFilter): any[] {
  nameFilter = nameFilter.toLowerCase()
  genderFilter = genderFilter.toLowerCase()

  return this.rows.filter(row => {
    const isPartialNameMatch = row.name.toLowerCase().indexOf(nameFilter) !== -1 || !nameFilter
    const isPartialGenderMatch = row.gender.toLowerCase().indexOf(genderFilter) !== -1 || !genderFilter
    return isPartialNameMatch && isPartialGenderMatch
  });
}

Stackblitz used for testing