Reputation: 11
I wanted to use table with filtering from Angular Material, but I can not filter complex types (Branch.category). Actual filter working only for subjectName.
TS:
export class Subject {
id: Number = null;
subjectName: String = '';
branch: Branch = new Branch;
}
export class Branch {
category: String = '';
}
displayedColumns: string[] = ['id', 'subjectName', 'category'];
dataSource;
subjects: Subject[];
constructor() {
this.subjects = [];
this.subjects.push({id:1, subjectName: 'Biology', branch: {category: 'science'}});
this.subjects.push({id:2, subjectName: 'physics', branch: {category: 'science'}});
this.subjects.push({id:3, subjectName: 'english', branch: {category: 'humanities'}});
this.dataSource = new MatTableDataSource(this.subjects);
}
applyFilter(filterValue: string) {
console.log(filterValue);
this.dataSource.filter = filterValue.trim().toLowerCase();
}
HTML:
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="search">
</mat-form-field>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> ID </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="subjectName">
<th mat-header-cell *matHeaderCellDef> subjectName </th>
<td mat-cell *matCellDef="let element"> {{element.subjectName}} </td>
</ng-container>
<ng-container matColumnDef="category">
<th mat-header-cell *matHeaderCellDef> category </th>
<td mat-cell *matCellDef="let element"> {{element.branch.category}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let element; columns: displayedColumns;"
[ngClass]="{'highlight': selectedRowIndex == element.id}"
(click)="highlight(element)"></tr>
</table>
I would like to make two separate filters: subjectName and category.
Upvotes: 1
Views: 813
Reputation: 1150
Welcome to StackOverflow, I think you might want to do a custom filter for your data table, you can do this by overriding the filterPredicate
property of the data source like this:
this.dataSource.filterPredicate = (data, filter) => {
const customField = data.branch.category;
return customField === filter;
}
This is just a small example for you and it may need some fix for you to work. Just let me know how it fits and we can work on it. You can read the docs for more info here.
Edit: Found this Github issue and I think it will be useful for you.
Upvotes: 2