Angular 4-在下拉列表中找到选定的值 [英] Angular 4 - find selected value in dropdown
问题描述
我正在使用Angular 4反应性表单创建下拉列表
I am using Angular 4 Reactive Forms to create a dropdown
<select id="city" formControlName="city" (change)="onCitySelect($event)" >
<option *ngFor="let city of cities" [ngValue]="city" >
{{ city }}
</option>
</select>
在下拉列表中选择一个值时,我想调用一个方法并显示所选值.
When a value is selected in the dropdown, I want to call a method and display the selected value.
这是我执行此操作的代码
Here is my code to do this
onCitySelect(event) {
console.log(event.target.value);
}
我希望它能打印下拉列表中所示的城市名称.但是,它似乎也显示索引号.例如,
I was expecting it to print the City name as shown in the dropdown. However, it seems it displays the index number as well. For instance,
2: London
不仅仅是下拉菜单中实际显示的London
.
Instead of just London
which is actually shown in the dropdown.
如何获取没有索引的城市名称?
How can I get the city name without the index?
推荐答案
如果您使用字符串或数字作为选项值并且不想使用[(ngModel)]="..."
,请使用[value]
代替[ngValue]
.
Use [value]
instead of [ngValue]
if you have a string or number as option value and don't want to use [(ngModel)]="..."
.
对于对象值,您始终应该使用[ngValue]
.
For object values you always should use [ngValue]
though.
这篇关于Angular 4-在下拉列表中找到选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!