The importance of the compare function in angular material select
The select does not load my previously selected option. Why?
In this article, one can learn the importance of the compare function compareWith
, a property used with the form control <mat-select>
for comparing option values with selected values.
When having a material select we often forget a few important elements or properties without which the select will not perform as wanted. In my demonstration, I will use a simple angular project with two components. On the first page, one can select a color, and then navigate to the next page and back to see if the select loads the previously selected option.
[A]. Prerequisites
Importing the API reference
The API reference for angular material select needs to be imported into the angular app module.
import {MatSelectModule} from '@angular/material/select';
Having a material form field
“It is designed to work inside of a
<mat-form-field>
element”, according to material.angular
Having the HTML view and module elements
We need to have a form field with a <mat-select>
which contains options held by the <mat-options>
element.
In our angular module, we need to have a form field element where we store our data, in our example the selected color from our colors list.
Storing our selected data
In our example, we store the data in the local storage of the browser. In other cases, this may be performed by a service that gets the data from the back-end server and loads it into the FormControl
.
The selected color is saved on a click event when navigating to the next page.
Besides this, we have two modules, the main module where we can select a color, and another for demonstration purposes.
[B]. The select does not load my previously selected option! Why & how to solve it
When navigating to the next page and then back to the main page, we can see that the data is stored correctly and loaded into our form field but we notice that the select field does not preload our option value.
This is because we are missing the use of the compareWith
function in the HTML view and thus the material select does not know how to compare and select our item from the other select options.
We can have multiple forms of comparison. In the above example, we specified the exact model in which we want to compare the two objects. The compareWith
function can be custom to our need with the restriction of returning a boolean
value.
[D]. Working example source code
Below you can see this in a simple example I have made, where if we do not write a compareWith
function the selected color will disappear after navigating back from the next page, even if it is loaded into the FormControl
.
See source code here:
[E]. Resources. Where to find more!
A detailed description of the property can be found in the official Angular documentation among more useful directives, and examples.