2

I'm using Angular4 tyring to associate ngValue to ngModel but getting Null. So kindly help me to connect ngValue to ngModel

<select name="gender" [(ngModel)]="nameForm.gender">
  <option [ngValue]="Male">Male</option>
  <option [ngValue]="Female">Female</option>
  <option [ngValue]="Others">Others</option>
</select>
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Vanishree
  • 21
  • 2

4 Answers4

2

wrap around single quates 'Male'

<select name="gender" [(ngModel)]="nameForm.gender">
    <option [ngValue]="'Male'">Male</option>
    <option [ngValue]="'Female'">Female</option>
    <option [ngValue]="'Others'">Others</option>
 </select>
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
1

In addition to other answers - I would populate options via *ngFor:

<option *ngFor="let item of genders" [ngValue]="item">{{ item }}</option>

And in the component's class simply create genders property like this:

genders: string[] = ['Male', 'Female', 'Others'];

If you want to use different key-value, you can create object array:

[{value: 'male', title: 'Male'}, {value: 'female', title: 'Female'}, ...]

And in your template:

<option *ngFor="let item of genders" [ngValue]="item.value">{{ item.title }}</option>

Last case - if you want to have options in your template, you can simplify binding syntax:

<option ngValue="Male">Male</option>
...
shohrukh
  • 2,989
  • 3
  • 23
  • 38
0

Bind to value attr directly:

<option [value]="'Male'">Male</option>

...note the single quotes inside [value].

PeS
  • 3,757
  • 3
  • 40
  • 51
0

use [value]

<select [(ngModel)]="nameForm.gender">
    <option [value]="'Male'">Male</option>
    <option [value]="'Female'">Female</option>
    <option [value]="'Others'">Others</option>
</select>
Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48