Angular — How to select a value by default on a dynamically populated select box
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.
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.