DEV Community


Angular's Selected Option binding

jwp profile image John Peters ・1 min read

The HTMLSelectElement contains Option Elements as shown below. Angular's *ngFor allows us to dynamically create multiple options at run time, but how do we select the proper option from the list of options?

   *ngFor="let option of row.options"
     = "row.optionToSelect === option.display"
   {{ option.display }}


The code above creates an HTMLOptionElement for each value in row.Options. If the row.optionToSelect equals the option.display property; that option is selected.

Angular Binding Syntax

//Two way Binding
[(selected)] = (some assertion)
//One way Binding 
[selected] = (some assertion)

One Way vs Two Way Binding

One-way binding means from Typescript to the View.

Two-way binding means Typescript can set values, and the User may change them.

Finding the Option Element's Property Names

When we go to MDN to determine which property of the Option element allows it to be selected.

We find this, the raw HtmlOptionElement binding.

<option selected = (some assertion)>OptionValue</option>

But in Angular we are not using raw element binding, rather we are using it's binding system.

Watching For the Change

// row is a *ngFor = 'let row of items' (binding)
// each row can have many fields
  (input)="onSelectInput(row, $event, select)"

Emitting the Change

onSelectInput(row, $event, select){
  let change = {
   changedValue: event?.target?.value
   rowBinding : row
   HtmlElement: select;

JWP 2020


Editor guide