angularngx-datatable

How allow multiple search with ngx-datatable


I'm using this https://github.com/swimlane/ngx-datatable/blob/master/demo/basic/filter.component.ts to help me create a search in my table.

My goal is to create an advanced search : filter by both gender and name value

  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;
}

I just copy my search creating a second function filtering by gender. However, both search works separately (erasing the restriction of the other) and I don't know how to fix it.

Here you can find my 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>

Solution

  • ... // 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