DEV Community

Cover image for Setting a Native Select Element's Default Option Using ngModel and 2 Way Binding
John Peters
John Peters

Posted on

Setting a Native Select Element's Default Option Using ngModel and 2 Way Binding

HTML

<select
 #sel="ngModel"
 [(ngModel)]="Id"
 (ngModelChange)="Id = onChange(sel)"
 >
  <option
   *ngFor="let option of options"
   [selected]="Id"
   [value]="option.id"
   >
   {{ option.display }}
  </option>
 </select>
Enter fullscreen mode Exit fullscreen mode

TypeScript Code

// The options array contains objects like these:
options = [
{ id: 1, display: "Primary" },
{ id: 2, display: "Something Else" }, 
{ id: 3, display: "Yet Another Option" }   

// The default current object is:
current = { id: 1, display: "Primary" } 

// The default option Id to Select
Id = 1;
... 
onChange(sel: NgModel) {
 let id = sel.viewModel;
 // Update current selection
 this.current = 
   this.options.find(
    (opt) => 
      opt.id.toString()=== id
   );
 return id;
}
Enter fullscreen mode Exit fullscreen mode

We once again utilize the ngModel triad as mentioned in other articles, this gives us the two way binding.

 // The pattern for the ngModel triad
 1) #sel="ngModel"
 2) [(ngModel)]="Id"
 3) (ngModelChange)="Id = onChange(sel)"
Enter fullscreen mode Exit fullscreen mode

The Option Binding
The ability to select an option based on an Id of the options array is done as shown here:

  // Each option look like this:
  // { id: 1, display: "Primary" }
  <option
   *ngFor="let option of options"
   // The "Id" in our code will be selected
   [selected]="Id" 
   // ...but bind to the option.id
   [value]="option.id" 
   >
   // Show the option.display
   {{ option.display }} 
  </option>
Enter fullscreen mode Exit fullscreen mode

Select Binding Explained

<select
 #sel="ngModel"
 [(ngModel)]="Id"
 (ngModelChange)="Id = onChange(sel)"
 >
Enter fullscreen mode Exit fullscreen mode

'sel' is the ngModel, and is passed to the 'onChange' function. [(ngModel)] uses our code's 'Id' property to track changes. Finally, our onChange function takes in the ngModel as a parameter.

'onChange' returns the ViewModel (ngModel's proposed change) which is the string representation of the 'Id'. 'onChange' also sets the 'current' object being selected. The 'current' property allows others to see both the id, and display values.

JWP2020 Native Select Option default Value in Angular

Top comments (0)