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

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

No responses yet

Write a response