通过Angular 2中的ngModel选择列表获取对象属性? [英] Getting object properties via ngModel select list in Angular 2?
问题描述
我在获取已从Angular 2(RC1)的选择列表中选择的对象的属性时遇到问题.采用以下语法:
I'm have a problem fetching the properties of an object which has been selected from a select list in Angular 2 (RC1). Take the following syntax:
<select required [(ngModel)]="model.plan">
<option selected="selected" disabled>Plan...</option>
<option *ngFor="#plan of plans" [value]="plan">{{ plan.name }}</option>
</select>
其中plans
被定义为对象数组:
Where plans
is defined as an array of objects:
[{ name: 'Plan 1' }, { name: 'Plan 2' }]
如果您尝试输出所选对象的键之一的值,则不会显示任何内容:
If you try and output the value of one of the keys of the selected object, nothing appears to be displayed:
<p>{{ model.plan?.name }}</p> // Shows nothing if a plan is selected
这是Angular2表单实时演示的一个分支,显示了此问题.从选择列表中选择计划2",然后看不到任何显示.
Here is a fork of the Angular2 form live demo, showing this problem. Select "Plan 2" from the select list, and see that nothing is displayed.
这是怎么回事?
推荐答案
要将对象用作值,请使用[ngValue]
而不是[value]
. [value]
仅支持字符串ID.
To use objects as value use [ngValue]
instead of [value]
. [value]
only supports string ids.
<select required [(ngModel)]="model"> <!-- <== changed -->
<option selected="selected" disabled>Plan...</option>
<option *ngFor="#plan of plans" [ngValue]="plan">{{ plan.name }}</option>
</select>
model
需要指向plans
中的一个元素以用作默认值(它必须是同一实例,而不是包含相同值的另一个实例).
model
needs to point to one of the elements in plans
to work as default value (it needs to be the same instance, not another instance containing the same values).
这篇关于通过Angular 2中的ngModel选择列表获取对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!