Creating a Conditional Clear Button on Our Angular Material Search Field

Ole Ersoy
Aug 26, 2019

--

Photo by David Carboni on Unsplash

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>

Demo

Brought To You By

--

--