Changing Angular Mat Icon Suffix Color Dynamically

Ole Ersoy
Dec 27, 2020

--

Image by Pexels from Pixabay

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:

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

No responses yet