If I hide the filter in mat-table with *ngIf I get error Cannot read property ‘value’ of undefined

I have developed a mat-table and with a button I want to show and hide my input filter area…
If I hide my filter area with *ngIf="showInputFilter" I get the error Cannot read property 'value' of undefined and nothing is shown in the table. How can I solve the problem?

My Code:


 <!-- File search -->
<button type="button" (click)="searchHandler()">
   <i class="fa fa-search" *ngIf="!(showInputFilter)" matTooltip="Filter your table"></i>

<div class="row" *ngIf="showInputFilter">
          <div class="col-md-12">
            <div class="filter-header">
              <mat-form-field class="filter-input">
                  <input matInput #filter (keyup)="applyFilter($event.target.value)" placeholder="Search" />
                <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="Löschen"></i></mat-icon>


 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 = '';

Source: Angular Questions