I am currently working with a mat table that has checkboxes for selecting all/row items and a filter function. When I apply a filter to the data source, I want to retrieve all the filtered data from this source.
After correctly applying the filter, I can see the filtered data in my mat table showing only the filtered items. However, when I try to select all rows using the "select all" checkbox in the mat-header, the filtered item rows are selected on the front end but upon checking through the debugger, I notice that while all rows are selected in the selected row array, the required filtered data rows are not present in the data source. How can I resolve this issue? If anyone knows of an example URL demonstrating this solution, please leave it in the comments.
Here is some sample code:
<mat-form-field appearance="outline">
<mat-label>Search</mat-label>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search">
<mat-icon matSuffix style="font-size: 16px;">search</mat-icon>
</mat-form-field>
<table mat-table #table [dataSource]="dataSource">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>
<mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()"
[indeterminate]="selection.hasValue() && !isAllSelected()">
</mat-checkbox>
</th>
<td mat-cell *matCellDef="let row">
<mat-checkbox (click)="$event.stopPropagation()"
(change)="$event ? selection.toggle(row) : null"
[checked]="selection.isSelected(row)">
</mat-checkbox>
</td>
</ng-container>
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef ><b>S.No.</b></th>
<td mat-cell *matCellDef="let element; let i=index">{{i+1}}</td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header="name">
<b>Office Name</b>
</th>
<td mat-cell *matCellDef="let element"> {{element.name }} </td>
</ng-container>
<ng-container matColumnDef="contactPerson">
<th mat-header-cell *matHeaderCellDef mat-sort-header="contactPerson"><b>Contact Person</b></th>
<td mat-cell *matCellDef="let element"> {{element.contactPerson}} </td>
</ng-container>
<ng-container matColumnDef="phone">
<th mat-header-cell *matHeaderCellDef mat-sort-header="phone"><b>Mobile No</b></th>
<td mat-cell *matCellDef="let element"> {{element.phone}} </td>
</ng-container>
TS code:
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
isAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
masterToggle() {
this.isAllSelected() ?
this.selection.clear() :
this.dataSource.data.forEach(row => this.selection.select(row));
}