Tudor-Radu Barbu
Tudor-Radu Barbu

Reputation: 494

Filters per column in a javascript table (Angular) combined results

I have this ngx-datatable for Angular that doesn't support filter by column. I would like to add an input filter for every column (some are strings, some are multiple choices etc) and combine them to a single filter so I can use it to get data with rxJs from the backend.

What I have for now:

This is the filter component on every column header:

<div class="input-group mb">
    <div class="input-group-addon">
        <span class="input-group-text" id="search-addon"><em class="icon-magnifier"></em></span>
    </div>
    <input aria-describedby="search-addon" id="order_id" aria-label="Customer" placeholder="Search" class="form-control" type="text" (keyup)='updateFilter($event)'>
</div>

The update filter function

updateFilter(event) {

  let columnName = event.currentTarget.id;

  const val = event.target.value.toString().toLowerCase();
  const filteredData = this.temp.filter(function(d) {
    return d[columnName].toString().toLowerCase().indexOf(val) !== -1 || !val;
  });
  this.rows= filteredData;
  this.table.offset = 0;
}

This works for every column. But how can I combine all the filters and start observing the API response?

Upvotes: 0

Views: 384

Answers (1)

Capricorn
Capricorn

Reputation: 2089

Your updateFilter() methods needs to values of all filter inputs, not only the one passed in via $event.

One way of doing can be to create an object filters in your component and two-way bind it's properties to your search inputs in the column headers. Listen to the ngModelChange event and trigger the actual filtering.

class MyComp {
   // Other stuff
   filters = {};

   filter = () => {
       // Do the filtering, all filters are set in this.filter object
   }
}

In your HTML template bind it and listen to the ngModelChange event to trigger the filtering whenever the value changes (better than using keyUp, as it also triggers when the content changes without a key being pressed, e.g. copy-pasting via context menu).

<input id="order_id" [(ngModel)]="filters.order_id" (ngModelChange)="filter()" ... />

Upvotes: 1

Related Questions