Angular2 RC2选择选项selectedIndex [英] Angular2 RC2 Select Option selectedIndex
问题描述
我有一个这样的非唯一选择选项,相同的值表示不同的东西.我们的数据就是这样,我只能进行数据拟合.
I got a non-unique select options like this, same value mean different thing. Our data is like that and I can only work to fit the data.
<select id="mySelect">
<option value = "1">Apple</option>
<option value = "2">Orange</option>
<option value = "3">Pineapple</option>
<option value = "1">Banana</option>
</select>
所以我可以通过设置selectedIndex来设置值.
So I can set value by setting selectedIndex.
document.getElementById("mySelect").selectedIndex = 3;
但是在Angular 2中,我在此语句类型'HTMLElement'上不存在属性'selectedIndex'.任何"上出错.
But in Angular 2, I got error on this statement "Property 'selectedIndex' does not exist on type 'HTMLElement'. any".
如何使用Angular2查找selectedIndex或如何解决它?
How can I find selectedIndex with Angular2 or how can I get around it?
更新: 我试图根据从数据库中检索到的其他数据,将设置默认值为选择选项.所以就像
Update: I am trying to set default value to the select option according to other data retrieved from the database. So it' something like
this.data$.subscribe(data => {
this.data = data;
if (data.someConditionMet) {
document.getElementById("mySelect").selectedIndex = 3;
}
},
error => this.errorMessage = <any>error);
请注意,选项中的值可以重复.但是条目不是.值"1"可以代表"Apple"或"Banana".这就是为什么我要使用索引而不是值.
Please note that the values in the options could be duplicate. But the entries are not. value "1" could represent either "Apple" or "Banana". That's why I want to use index rather than value.
推荐答案
通常,您将在Angular 2中采用另一种方法.您将让数据控制dom,而不是相反.
Typically, you would take a different approach in Angular 2. You would have your data control the dom, not the other way around.
类似这样的东西:
<select id="mySelect">
<option *ngFor="let dataValue of myDataArray" value = "dataValue.value" (click)="onSelected(dataValue)">{{dataValue.Text}}</option>
</select>
然后在您的组件中有一个处理程序onSelected
,该处理程序知道选择了哪个数据项.
And then have a handler onSelected
in your component, which knows which data item was selected.
您要基于数据进行默认选择吗?
只需将[selected]="someJavascriptExpression"
添加到option
元素.
例如:[selected]="dataValue.value === someCond && dataValue.text === someOtherCond"
.是什么使每个option
元素根据您的数据而唯一.
You want a default selection based on your data?
Just add [selected]="someJavascriptExpression"
to the option
element.
Eg: [selected]="dataValue.value === someCond && dataValue.text === someOtherCond"
. Whatever makes each option
element unique based on your data.
这篇关于Angular2 RC2选择选项selectedIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!