Angular — How to select a value by default on a dynamically populated select box

Photo by Valery Sysoev on Unsplash

With HTML it’s very easy to preselect a value by default on a select box using the selected attribute as follows.

Recently I found myself in a situation where I had to achieve the same in Angular, but on a dynamic select box which was initially populated as follows.

Now since the option is in a loop, applying the selected attribute will set each option as selected. So to avoid that I used the ternary operator together with the Angular property binding technique, to check if the populated select box has an option with the same value as the one that I want to select by default. Here is the syntax of the ternary operator in JavaScript/typescript.

variablename = (condition) ? value1:value2

if the condition is true, variablename will have a value of value1 else it will have a value of value2.

It would be easy if I knew the value that should be preselected by default, but unfortunately all values are coming from a database in a column with autoincremented PK, and I was comparing the PK to the values populated on the select box dynamically. so I ended-up doing the following:

The pk variable comes from the component, so the ternary operator will crosscheck in the select box for an option that has the same value as the dynamic PK value coming from the database, then set it as selected, otherwise it will put an empty string.

This was just a quick fix, if you know a better way to do this, kindly let me know in comment.

If programming was magic, I would be the Wand and you the Bright. If it was a form of communication, I would be a multilingual who speaks Java, Python, C#, etc.