0

I can't refresh the datasource for my mat table. I've declared it like this:

dataSource: MatTableDataSource<Custom_Data> = new MatTableDataSource();

where Custom_Data is an interface I've created with custom fields. In ngOnInit I get the data from server and do this:

this.networkService.getCapitoliSelectItem(this.idContesto).subscribe(d => {
     this.tableData= d;
     this.tableData.forEach(c => {
        //manipulate data
     });
     this.dataSource = new MatTableDataSource(this.tableData);
     //put here to trigger detection of changes, not workin
     this.changeDetector.detectChanges(); 
}

No data is shown on the table. Then I have a filter method, because in the header of my table I have two input fields that I use to filter the data in my table. In this case, if I write something the method filter is called and my data display in the table and everything works fine.
The filter method is:

applyFilter(filterValue: string, column: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    if(Number(filterValue.length) != 0){
        this.dataSource.data = this.tableData.filter(d => d[column].toLowerCase().indexOf(filterValue)>-1);
    } else {
        this.dataSource.data = this.tableData;
    }
}

Why is this working and not the ngOnInit method? I've also tried this.dataSource.data = this.tableData instead of this.dataSource = new MatTableDataSource(this.tableData);, but didn't work.

igg
  • 2,172
  • 3
  • 10
  • 33
Usr
  • 2,628
  • 10
  • 51
  • 91
  • Could prepare a working example in stackblitz? Doesn't have to get data from an external server, you can prepare some mock data as an Observable using the of() operator. – igg Dec 12 '19 at 11:23
  • @IraklisGkougkousis I've prepared a Stackblitz but it's working there... I don't really know why, I do the same operations. https://stackblitz.com/edit/angular-1cprka . The only different thing is that my table is in a modal, but it should behave like a normale component when it is loaded, I guess?... – Usr Dec 12 '19 at 13:33
  • What does the changeDetector.detectChanges() do? – igg Dec 12 '19 at 13:52
  • @IraklisGkougkousis basically it checks for all the views that have to be updated and re-renders them. It's from angular-core. – Usr Dec 12 '19 at 13:56
  • Does this help? https://stackoverflow.com/questions/45236671/why-do-i-need-to-call-detectchanges-with-the-default-change-detection-strategy – igg Dec 12 '19 at 14:03
  • Thanks, I've tried with zone but it isn't working. – Usr Dec 12 '19 at 14:09
  • Sorry I can't help. – igg Dec 12 '19 at 14:12

0 Answers0