ngValue返回索引和值 [英] ngValue returning index and value
问题描述
使用[ngValue]从选择返回的值是索引和值的串联
The value coming back from a select using [ngValue] is a concatenation of index and value
如果我使用这个
<select (change)="selectType($event)" name="type" >
<option *ngFor="let type of types" [ngValue]="type.value" >{{type.display}}</option>
</select>
然后我用它来获取所选选项的值
and then I use this to get the value of the selected option
selectType (e) {
this.type = e.target.options[e.target.selectedIndex].value;
}
我的价值观看起来像这样
My values look like this
0: type1
1: type2
2: type3
...
我将如何获得价值? 似乎ngValue将索引AND值放在value参数中.
how would I just get the value? It seems ngValue is putting the index AND value in the value parameter.
推荐答案
由于您正在处理change
DOM事件,因此参数$event
是
Since you are handling the change
DOM event, the parameter $event
is the Event object supplied by the DOM, not the value of the option set with ngValue
.
如果改为处理ngModelChange
Angular事件,则参数$event
将是该选项的值.如果只需要在组件类中设置type
的值,也可以对ngModel
使用双向绑定.
If you handled the ngModelChange
Angular event instead, the parameter $event
would be the value of the option. You could also use two-way binding with ngModel
if you only need to set the value of type
in the component class.
以下是各种选项.您可以在此stackblitz 中进行尝试.
Here are the various options. You can try them in this stackblitz.
- 将事件目标的值传递给
selectType
:
<select (change)="selectType($event.target.value)" name="type">
- 使用
ngModel
(无selectType
)通过双向绑定设置值:
- Setting the value with two-way binding using
ngModel
(withoutselectType
):
<select [(ngModel)]="type" name="type">
- 分别处理
ngModel
和ngModelChange
(如果在selectType
中进行了更多处理):
- Handling
ngModel
andngModelChange
separately (if more processing is done inselectType
):
<select [ngModel]="type" (ngModelChange)="selectType($event)" name="type">
这篇关于ngValue返回索引和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!