Search code examples
angularngx-datatable

ngx-datatable in angular2 filter back results on backspace


I am using ngx-datatable (http://swimlane.github.io/ngx-datatable/#filter) in my angular project and trying to add a filter. The filter is added successfully on the column specified, however when I erase the filter characters with backspace, my original list data is not populated back.

My HTML:

<input
    type='text'
    style='padding:8px;margin:15px auto;width:30%;'
    placeholder='Type to filter the task name column...'
    (keyup)='updateFilter($event)'
  />
<div>
    <ngx-datatable  class="material"
    [rows]="tasks"
    [columns]="columns">
</ngx-datatable>

and in my component I have:

rows = [];
columns = [
{ name: 'Id' },
{ name: 'What task', prop: 'what_task' },
{ name: 'Budget', prop:'tentative_budget' }
];

temp = [];
ngOnInit() {

    this.taskListService.getTasks().subscribe(
        tasks => {
            console.log(tasks);
            this.tasks=tasks;
            this.tableData=this.tasks;
            this.tableModel.addAll(this.tableData);

        }
        )
}

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

    // filter our data
    const temp = this.tasks.filter(function(d) {
        console.log(d.what_task.toLowerCase().indexOf(val) !== -1 || !val)
        return d.what_task.toLowerCase().indexOf(val) !== -1 || !val;
    });

    // update the rows
    this.tasks = temp;

}

What am I missing?


Solution

  • You made a simple logical mistake. Try something like this

    HTML

    <ngx-datatable  class="material"
    [rows]="tableData"
    [columns]="columns">
    

    TS

    updateFilter(event) {
    const val = event.target.value.toLowerCase();
    
    // filter our data
    const temp = this.tasks.filter(function(d) {
        console.log(d.what_task.toLowerCase().indexOf(val) !== -1 || !val)
        return d.what_task.toLowerCase().indexOf(val) !== -1 || !val;
    });
    
    // update the rows
    this.tableData= temp;
    
    }