3

I use the name attribute and the ngModel directive as an easy way to get form values in an Angular 2 app:

<input type="text" name="firstName" ngModel>

But I'm having a problem when using this approach in a select:

<select name="gender" ngModel>

The select with a ngModel renders with a blank/empty option.

Without ngModel:

enter image description here

With ngModel:

enter image description here

Here's a plunker: http://plnkr.co/edit/hwF2U7WHp1U8IQnVGEXv?p=preview

Am I missing something or is this a bug?

nunoarruda
  • 2,679
  • 5
  • 26
  • 50
  • That's not an empty option added, just the default value not matching any option. What do you add `ngModel` for anyway? – Günter Zöchbauer Sep 12 '16 at 09:12
  • With NgModel, its empty because its bind to your model value. if you want any gender to be selected by default then set the gender value to your model. e,.g. [(ngModel)]="Model.value" two way binding. – Jeet Sep 12 '16 at 09:13
  • Possible duplicate of [Why does angularjs include an empty option in select](http://stackoverflow.com/questions/12654631/why-does-angularjs-include-an-empty-option-in-select) – Tjaart van der Walt Sep 12 '16 at 09:13

1 Answers1

1

If you use

<select name="gender" [(ngModel)]="gender">

with

gender: string = 'male';

You get the desired result. If you use ngModel this way, you also shouldn't need the getFormData method.

Plunker example

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567