I have implemented a filter function in my Angular project to display only specific data in a mat-table based on the filter criteria.
Within my mat-table, I am providing an array of objects to populate the table.
The filtering function I have created looks like this:
import {Component, ViewChild} from '@angular/core';
import {MatTable} from '@angular/material';
@ViewChild('TABLE') table: MatTable<any>;
dataSource: CandidateDataSource | null;
filterTableFunction(form) {
let result = this.dataSource.data.filter(obj => {
if (form.userValidation === true) {
return obj.candidateState === 'userValidation';
}
});
this.dataSource.filteredData = [...this.result];
this.table.renderRows();
console.log('The updated data source is:', this.dataSource.filteredData);
console.log('The filtered result is:', result);
}
While checking the console, I noticed that the new filtered array is accurate, but the table does not reflect these changes.
I attempted to make "result" a global variable, but unfortunately, it did not resolve the issue.
UPDATE:
The initial solution did not solve the problem as expected.
Updated code snippet:
// public
public result = [];
filterTableFunction(form) {
console.log('#1', this.dataSource.data); //logs an array of objects
this.result = this.dataSource.data.filter(obj => {
if (form.userValidation === true) {
return obj.candidateState === 'userValidation';
}
});
console.log('#2' , this.result); // New array containing the objects with candidateState === 'userValidation'
this.dataSource.data = [...this.result];
this.table.renderRows();
console.log('#3', this.dataSource.data) // Shows replaced array from above line with the correct result
}