Angular 4 - 在下拉列表中找到选定的值 [英] Angular 4 - find selected value in dropdown

查看:27
本文介绍了Angular 4 - 在下拉列表中找到选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular 4 Reactive Forms 创建下拉菜单

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?

推荐答案

使用 [value] 而不是 [ngValue] 如果你有一个字符串或数字作为选项值并且不想使用 [(ngModel)]="...".

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆