0

I have a form that has input fields and and some select dropdowns. All the input fields are being populated correctly from the input object, but the dropdowns are not being selected to the correct value, and always have a blank option first.

This is what the template looks like:

<div class="form-group">
    <label for="state">State:</label>
    <select class="form-control formField"  id="state" required [(ngModel)]="user.state" name="state">
        <option *ngFor="let state of states" [ngValue]="state">{{state}}</option>
    </select>
</div>

I cant figure out what I am missing.

user.state is a string that contains a 2-letter state abbreviation. States is an array of US states using 2-letter abbreviation.

aynber
  • 22,380
  • 8
  • 50
  • 63
MLefebvre
  • 21
  • 10
  • What's in "state" variable ? Because [value]="..." only supports string values and [ngValue]="..." supports any type. Take a look at https://stackoverflow.com/questions/35945001/binding-select-element-to-object-in-angular-2 – Toodoo Dec 15 '17 at 18:39
  • user.state='NY' states is an array of US 2-letter states. – MLefebvre Dec 16 '17 at 03:05
  • I just changed my code to use [value] instead of [ngValue] since I am just comparing strings and still the select is not pre-selected. – MLefebvre Dec 16 '17 at 05:27

1 Answers1

1

The best way I've found is as follows:

<div class="form-group">
<label for="state">State:</label>
<select class="form-control formField"  id="state" required [(ngModel)]="user.state" name="state">
    <option [ngValue]="undefined" disabled selected>Select a State</option>
    <option *ngFor="let state of states" [ngValue]="state">{{state}}</option>
</select>

The disabled attribute does not allow that option to be selected from the dropdown. Hope this helps.

Justin
  • 683
  • 8
  • 24