Material Angular Table Sorting,Filter Part 2
Do refer materiel table part 1 here, we discussed further.
Sorting
To add sorting behavior to the table, add the matSort directive to the table and add mat-sort-header to each column header cell that should trigger sorting.
Step 1: Add matSort directive in table tag as below
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">Step 2: Add mat-sort-header directive to the column which you want to add the sorting,
<ng-container matColumnDef="name">Step 3: In component add import MatSort from material
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name</th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
import {MatSort} from '@angular/material';Step 4: to add MatSort view child in component
@ViewChild(MatSort) custsort: MatSort;Step 5: Assign the custsort to MatTableDataSource's objects sort property in ngOnInit()
ngOnInit() {Step 6: Run the project see the result
this.dataSource.sort = this.sort;
}
Filtering
If you are using the MatTableDataSource, simply provide the filter string to the MatTableDataSource. The data source will reduce each row data to a serialized form and will filter out the row if it does not contain the filter string. By default, the row data reducing function will concatenate all the object values and convert them to lowercase.
Step 1: Add applycustomFilter method in the corresponding component
applycustomFilter(filterValue: string) {
this.custSource.filter = filterValue.trim().toLowerCase();
}
Step 2: Add a Material input right above the mat table and handle the keyup event
<mat-form-field>
<input matInput (keyup)="applycustomFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
Step 3: Run the project see the result
0 Comments