After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use
*ngIf="showInputFilter"
to hide the filter area, I receive the error message Cannot read property 'value' of undefined
and the table remains empty. How can I fix this problem?
This is my code:
HTML:
<!-- File search -->
<button type="button" (click)="searchHandler()">
<i class="fa fa-search" *ngIf="!(showInputFilter)" matTooltip="Filter your table"></i>
</button>
<div class="row" *ngIf="showInputFilter">
<div class="col-md-12">
<div class="filter-header">
<mat-form-field class="filter-input">
<label>
<input matInput #filter (keyup)="applyFilter($event.target.value)" placeholder="Search" />
</label>
<button mat-icon-button matSuffix aria-label="clear" *ngIf="filter.value" (click)="filter.value=''; applyFilter('');">
<mat-icon class="filter-remove"><i class="fa fa-trash" id="remove-icon" matTooltip="Delete"></i></mat-icon>
</button>
</mat-form-field>
</div>
</div>
</div>
TS:
public showInputFilter = false;
// Click to open the input filter
searchHandler() {
this.showInputFilter = !this.showInputFilter;
}
// Filter
public applyFilter(filterValue: string) {
filterValue = filterValue.trim();
filterValue = filterValue.toLowerCase();
this.dataSource.filter = filterValue;
this.isTableHasData = this.dataSource.filteredData.length > 0;
}
public cancelFilter() {
this.dataSource.filter = '';
this.filter.nativeElement.value = '';
}