问题
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>
回答1:
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>
回答2:
Bind to value
attr directly:
<option [value]="'Male'">Male</option>
...note the single quotes inside [value]
.
回答3:
use [value]
<select [(ngModel)]="nameForm.gender">
<option [value]="'Male'">Male</option>
<option [value]="'Female'">Female</option>
<option [value]="'Others'">Others</option>
</select>
回答4:
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>
...
来源:https://stackoverflow.com/questions/51839685/associate-select-value-to-ngmodel-in-angular-4