Looking to develop a versatile table that accepts tableColumns and dataSource as @Input(). I want the ability to add custom filtering for each table column. Currently, I've set up the initialization of the table FormGroup and retrieving its value for filtering. However, beyond this point, I'm unsure of how to proceed. I've experimented with implementing pipes and exploring similar solutions online, but they all require knowledge of my tableColumns (which are dynamically created).
Below is a snippet of my code:
<table mat-table [dataSource]="dataSource">
<ng-container *ngFor="let col of tableColumns; let i = index" [matColumnDef]="col.key">
<ng-container>
<th class="header" mat-header-cell *matHeaderCellDef>
<span *ngIf="!col.config">
{{ col['display'] }}
</span>
<form [formGroup]="form">
<mat-form-field *ngIf="!col.config" class="filter">
<input matInput placeholder="Filter" formControlName="{{tableColumns[i].key}}">
</mat-form-field>
</form>
</th>
<td mat-cell *matCellDef="let element; let row">
<ng-container>
{{ element[col.key] }}
</ng-container>
</td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="keys"></tr>
<tr mat-row *matRowDef="let row; columns: keys"></tr>
</table>
My TypeScript file includes:
@Input() tableColumns: GenericTableColumn[] = []
@Input() dataSource: Array<object> = []
ngOnInit(): void {
this.initFormControls()
this.registerFormChangeListener()
}
initFormControls() {
const formGroup: FormGroup = new FormGroup({})
this.tableColumns.forEach((column) => {
if (column.key !== 'actions') {
let control: FormControl = new FormControl('')
formGroup.addControl(column.key, control)
}
})
this.form = formGroup
}
The plan was to create a function to convert the dataSource input into a MatTableDataSource and apply a custom filter predicate. Here's a rough idea:
registerFormChangeListener(){
const tableDataSource = new MatTableDataSource(this.dataSource)
tableDataSource.filterPredicate((tableDataSource, filter) => {
// need to filter by object key value here
})
}
Sample dataSource:
{
{
"id": "1",
"name": "someValue1",
"someOtherKey": "someOtherValue"
},
{
"id": "2",
"name": "someValue2",
"someOtherKey": "someOtherValue2"
},
{
"id": "3",
"name": "someValue3",
"someOtherKey": "someOtherValue2"
}
}
Expected filter object:
{
"id": "",
"name": "someValue1",
"someOtherKey": "someOtherValue2"
}
Hoping to achieve filtered results like:
const fitleredResults = [
{
"id": "1",
"name": "someValue1",
"someOtherKey": "someOtherValue"
},
{
"id": "2",
"name": "someValue2",
"someOtherKey": "someOtherValue2"
}
]
Appreciate any guidance!