DEV Community

Cover image for Angular Form Controls and [ngValue] binding with Option elements
John Peters
John Peters

Posted on • Updated on

Angular Form Controls and [ngValue] binding with Option elements

New Discovery
Use ngModel instead!


 <select
   formControlName="state"  
 >
 <option
   *ngFor="let state of states"
   [selected]="state.name === address.state"
   [ngValue]="state.name"
 >
 {{ state.name }}
 </option>
Enter fullscreen mode Exit fullscreen mode

Here we show a Select control allowing the user to pick a State. The Options are created via the *ngFor statement using the array of states.

Notice the [ngValue] directive? It serves to stop the Select control from pseudo-selecting the first option in the list. If we are using formControl validation, that first psuedo-selected Option is also marked invalid! Oh yes, one other thing, the [selected] test doesn't work either.

This tells us that even when we specify the value to show 'state.name' it's not enough.

JWP2020

Top comments (0)