Typescript Angular2 RC2选择选项selectedIndex
我得到了这样一个非唯一的选择选项,相同的值意味着不同的东西。我们的数据是这样的,我只能努力拟合数据 苹果 橙色 菠萝 香蕉 所以我可以通过设置selectedIndex来设置值Typescript Angular2 RC2选择选项selectedIndex,typescript,angular,Typescript,Angular,我得到了这样一个非唯一的选择选项,相同的值意味着不同的东西。我们的数据是这样的,我只能努力拟合数据 苹果 橙色 菠萝 香蕉 所以我可以通过设置selectedIndex来设置值 document.getElementById("mySelect").selectedIndex = 3; 但在Angular 2中,我在语句属性“selectedIndex”上出错,该属性在类型“HtmleElement”上不存在。任何 如何使用Angular2查找selectedIndex或如何绕过它 更新: 我
document.getElementById("mySelect").selectedIndex = 3;
但在Angular 2中,我在语句属性“selectedIndex”上出错,该属性在类型“HtmleElement”上不存在。任何
如何使用Angular2查找selectedIndex或如何绕过它
更新:
我试图根据从数据库检索到的其他数据将默认值设置为select选项。所以有点像
this.data$.subscribe(data => {
this.data = data;
if (data.someConditionMet) {
document.getElementById("mySelect").selectedIndex = 3;
}
},
error => this.errorMessage = <any>error);
请注意,选项中的值可能重复。但这些条目并非如此。值1可以表示苹果或香蕉。这就是为什么我想使用索引而不是值。通常,在Angular 2中,您会采用不同的方法。您可以让数据控制dom,而不是反过来 大概是这样的:
<select id="mySelect">
<option *ngFor="let dataValue of myDataArray" value = "dataValue.value" (click)="onSelected(dataValue)">{{dataValue.Text}}</option>
</select>
然后在组件中选择一个处理程序onSelected,它知道选择了哪个数据项
您想要基于数据的默认选择吗?
只需将[selected]=someJavascriptExpression添加到option元素。
例如:[选定]=dataValue.value==someCond&&dataValue.text==someOtherCond。根据您的数据,使每个选项元素唯一的选项。只需使用select的模型来设置或获取当前值: {{dataValue.Text} 在您的组件中:
export class ComponentA {
selectedValue: number = -1;
// ...
this.data$.subscribe(data => {
this.data = data;
if (data.someConditionMet) {
selectedValue = 3;
}
},
error => this.errorMessage = <any>error
);
我发现了一些有趣的东西 对于非唯一选择选项,Angular2将转换值,并自动添加索引。例如,从
<select id="mySelect">
<option value = "1">Apple</option>
<option value = "2">Orange</option>
<option value = "3">Pineapple</option>
<option value = "1">Banana</option>
</select>
到
所以在我的代码中,我可以
this.data$.subscribe(data => {
this.data = data;
if (data.someConditionMetForBanana) {
ngModelBoundSelectedValue = "3: 1";
}
},
error => this.errorMessage = <any>error);
霍尔蒂吉的评论是正确的。安格拉尔2号为我们做了这件美妙的事情 使用$event.target.selectedIndex。设selIdx=0。那么
<select (change)="selIdx = $event.target.selectedIndex;"> Select One
<option *ngFor="let a of array;let i = index;" value="{{ a.val }}" [selected]="selIdx == i">
{{ a.desc }}
</option>
</select>
霍尔蒂,我已经这么做了。我试图在从数据库检索数据时设置默认值。我刚刚更新了我的问题。还有什么进一步的意见吗?非常感谢。只需将[selected]=dataValue.value==someCondition添加到选项元素。值1可以表示苹果或香蕉。这就是为什么我想使用索引而不是值。我有这个想法,请注意选项列表中的值是非唯一的。因此,使用[ngModel]=selectedValue可能会得到不想要的结果。如果有重复的条目,这个select还有什么用?那么就用@hholtij的评论吧……关于条目的某些内容必须是唯一的,否则选择将毫无意义。如果不是值,那么可能是值和文本的组合。基本上,[selected]属性中可以有任何javascript表达式,例如[selected]=dataValue.value==someCond&&dataValue.text==someothercond。我不认为它是重复的。请仔细阅读。将默认值设置为非唯一选项。在尝试使用selectedIndex属性之前,需要将document.getElementByIdmySelect强制转换为类HTMLSelectElement:document.getElementByIdmySelect.selectedIndex=3;
<select (change)="selIdx = $event.target.selectedIndex;"> Select One
<option *ngFor="let a of array;let i = index;" value="{{ a.val }}" [selected]="selIdx == i">
{{ a.desc }}
</option>
</select>