Creating a Conditional Clear Button on Our Angular Material Search Field
Updated Version
There is an updated version of this article here:
Scenario
We have a material search field and we want to add a clear button to render on the condition that the search field is populated.
<mat-form-field> <input [(ngModel)]="searchField" matInput placeholder="Search" autocomplete="off"></mat-form-field>
Approach
Just add *ngIf="searchField"
to the mat icon button:
<mat-form-field>
<input [(ngModel)]="searchField" matInput placeholder="Search" autocomplete="off">
<button mat-button mat-icon-button matSuffix (click)="clearSearchField()" *ngIf="searchField">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>