Javascript 双向绑定到Angular 2中的select元素不会在第一次渲染时设置selected元素
在Angular 2.0(rc 1)中,我使用以下代码将对象[]绑定到选择列表。 问题在于,最初在呈现“选择”列表时,它没有预先选择适当的值/索引 在下面的代码示例中,“ma”是组件的实际类变量。ma有一个SelectedItemType属性,它是myItemTypes对象数组中的一个对象Javascript 双向绑定到Angular 2中的select元素不会在第一次渲染时设置selected元素,javascript,angularjs,angular,angular2-template,Javascript,Angularjs,Angular,Angular2 Template,在Angular 2.0(rc 1)中,我使用以下代码将对象[]绑定到选择列表。 问题在于,最初在呈现“选择”列表时,它没有预先选择适当的值/索引 在下面的代码示例中,“ma”是组件的实际类变量。ma有一个SelectedItemType属性,它是myItemTypes对象数组中的一个对象 <select class="form-control" [(ngModel)]="ma.SelectedItemType"> <option *ngFor='let ite
<select class="form-control" [(ngModel)]="ma.SelectedItemType">
<option *ngFor='let item of myItemTypes'
[ngValue]='item'>{{item.Label}}
</option>
</select>
{{item.Label}
我尝试过使用[selected]/[attr.selected]属性,但没有什么区别。
其他一些信息:
如果使用下面的代码绑定到Type属性(字符串值),而不是对象(工作正常):
{{item.Label}
但是,我真的希望能够与对象进行双向数据绑定。你能看到我这里可能缺少的东西吗?
ma。selectedItemType
必须引用myItemType
的项目。它必须指向同一个实例,另一个实例即使具有相同的内容也无法工作。Hi。谢谢你,但我不知道如何才能让它指向同一个实例。问题是myItemTypes是一个单独的myItemType对象列表,我正在使用它填充选择列表。selectedItemType来自另一个@Input对象。它们的“类型”相同,但我不确定如何让它们指向同一个实例。您可以在myItemTypes
中查找实例,方法是将项目与您自己输入的值进行比较,如ma.selectitemtype
ma.SelecteItemType=myItemTypes.find(val=>val.label==myInput.label&&val.xxx==val.xxx)
<select class="form-control" [(ngModel)]="ma.SelectedItemType.Type">
<option *ngFor='let item of myItemTypes'
[value]='item.Type'>{{item.Label}}
</option>
</select>