Changing Angular Mat Icon Suffix Color Dynamically

Scenario

We have defined a search suffix icon like this for our search field:

<mat-icon>search</mat-icon>

And we want to change the icon color to primary when the field is focused and back to the original color when the field is not focused.

Approach

Reference the search field by adding #searchInput to the search input element:

<input matInput #searchInput="matInput"autocomplete="off"/>

Set the color property to primary when the searchInput field is focused:

<mat-icon [color]="searchInput.focused ? 'primary' : ''" matSuffix>search</mat-icon>

Here’s an example containing complete markup:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store