ngValue返回索引和值 [英] ngValue returning index and value

查看:50
本文介绍了ngValue返回索引和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用[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.

  1. 将事件目标的值传递给selectType:

    <select (change)="selectType($event.target.value)" name="type">

  1. 使用ngModel(无selectType)通过双向绑定设置值:
  1. Setting the value with two-way binding using ngModel (without selectType):

    <select [(ngModel)]="type" name="type">

  1. 分别处理ngModelngModelChange(如果在selectType中进行了更多处理):
  1. Handling ngModel and ngModelChange separately (if more processing is done in selectType):

    <select [ngModel]="type" (ngModelChange)="selectType($event)" name="type">

这篇关于ngValue返回索引和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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