I call up the data via a service and get it to my mat-table. I would like to filter them. Unfortunately my code does not work. Where is the error? Can you please help me?
My Code:
<div class="filter-header">
<mat-form-field class="filter-input">
<label>
<input matInput #filter (keyup)="applyFilter($event.target.value)" placeholder="Durchsuchen" />
</label>
<button mat-icon-button matSuffix aria-label="clear" *ngIf="filter.value" (click)="filter.value=''; applyFilter('');">x
</button>
</mat-form-field>
</div>
export class TableBasicExample {
displayedColumns: string[] = ['id', 'userId', 'title', 'completed'];
public dataSource: MatTableDataSource<Data> = null;
// Overview of the ViewChilds
@ViewChild('filter', {static: true}) filter: ElementRef;
@ViewChild('tableWrapper', {static: true}) tableWrapper: ElementRef;
constructor(private service : APIServiceService){
this.service.getData().subscribe(data => {
this.dataSource = data;
});
}
// Filter
public applyFilter(filterValue: string) {
filterValue = filterValue.trim();
filterValue = filterValue.toLowerCase();
this.dataSource.filter = filterValue;
console.log(filterValue.lastIndexOf);
}
public cancelFilter() {
this.dataSource.filter = '';
this.filter.nativeElement.value = '';
}
}
My Work in Stackblitz
You have to create new MatTableDataSource
.
Updating the following line would do the trick for you
this.dataSource = new MatTableDataSource(data);
instead of
this.dataSource = data.
Updated the stackblitz