Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

angular2 forms - Getting object properties via ngModel select list in Angular 2?

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>

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

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.

What's going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 example

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...