loading...

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?

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

</option

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

Emitting the Change


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

JWP 2020

Posted on by:

jwp profile

John Peters

@jwp

Angular, React, Typescript and JavaScript. The wave of now! Ok Vue too!

Discussion

markdown guide