Default select option in Angular 5

Hi everyone,

For this first post we’ll be working on selecting a default option on select menu with Angular 5.

But first, and as you may know, to select an option with HTML only, you just have to use ‘selected’ attribute on your option to get it selected :


When working with Angular, you can show users simple string values but interact with your model in an object way.

Let’s take a simple example. Imagine you retrieve a keyboard layouts list from an API, a constant or whatever data source. You want to display the default keyboard user previously chose.

Simple select within a form :

In component file ;

This way select value binds to keyboard variable. However this is not enough for Angular to select the correct option.

To achieve this you have to implement a custom function that allows to compare your model with loop current value and determine whether option should be selected or not.

Indeed to compare object, Angular compares their identity. Thus two objects that come from a different source can have same data but different identity.

This directive called SelectControlValueAccessor is available with module ‘@angular/foms’¬†imported.

It can be used on a select within a form element via attribut :

As shown above, function compareFn simply returns a boolean, true if both objects are equals, false if not.


Don’t hesitate to leave a comment if this article was useful to you !



Leave a Reply

Your email address will not be published. Required fields are marked *