通过 Angular 2 中的 ngModel 选择列表获取对象属性? [英] Getting object properties via ngModel select list in Angular 2?

查看:32
本文介绍了通过 Angular 2 中的 ngModel 选择列表获取对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在获取从 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 表单现场演示的一个分支,展示了这个问题.从选择列表中选择Plan 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>

Plunker 示例

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屋!

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