DEV Community

John Peters
John Peters

Posted on

Angular's Selected Option binding

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?

<option
   *ngFor="let option of row.options"
   [(selected)]  
     = "row.optionToSelect === option.display"
   >
   {{ option.display }}

</option

Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
<select>
  #select                  
  (input)="onSelectInput(row, $event, select)"
</select>
Enter fullscreen mode Exit fullscreen mode

Emitting the Change


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

Enter fullscreen mode Exit fullscreen mode

JWP 2020

Top comments (0)