Home > OS >  Angular dataSource filter not working after updating dataSource
Angular dataSource filter not working after updating dataSource

Time:08-13

I am working with a MatTable in Angular and I have added a search filter function like this:

  onSearch(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

My dataSource is initialized like this:

dataSource = new TableVirtualScrollDataSource<GroupPerms>;

// this function is called on init once data from the backend comes in
initData(data: Group[]){
    for(let i = 0; i < data.length; i  ){
      this.myData.push({
        checked: false,
        permission: '',
        group: data[i]
      })
    }
...
 this.dataSource = new TableVirtualScrollDataSource(this.myData);
}

This works until I call a separate function which modifies the data:

onChange(){
  this.dataSource.filter = '';
  // does some stuff to the myData
...
  this.dataSource = new TableVirtualScrollDataSource(this.myData);
}

After this function is called the search filter doesn't work anymore. When you type in a search query it shows no data, if you leave the query blank it shows all the data in the table (as expected). If you enter the first letter of the search query that was entered before the onChange() function was called it also shows all data in the table.

Does anyone know how to fix this or why this is happening

(btw. TableVirtualScrollDataSource should work just like MatTableDataSource)

CodePudding user response:

Whenever data changes you were creating new TableVirtualScrollDataSource instance, since new instance created it's not connected with filter. Instead you can initialize TableVirtualScrollDataSource once and change data using data property on it.

initData(data: Group[]){
    for(let i = 0; i < data.length; i  ){
      this.myData.push({
        checked: false,
        permission: '',
        group: data[i]
      })
    }
...
 this.dataSource.data = this.myData;
}
  • Related