Getting object properties via ngModel select list

2019-02-08 07:20发布

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?

2条回答
成全新的幸福
2楼-- · 2019-02-08 07:59

As far as I can see, there's still an issue with two-way binding to a select. So try this:

Template

<select required [(ngModel)]="model.plan" (change)="setPlan($event.target.value)">
    <option selected="selected" disabled>Plan...</option>
    <option *ngFor="#plan of plans" [value]="plan.name">{{ plan.name }}</option>
</select>

Component Class

setPlan(value) {
    //if you're on older versions of ES, use for-in instead
    var plan = this.plans.find(p => p.name = value);

    if(plan) { this.model.plan = plan; }
}

Couldn't try it, for some reason plunkr has never worked for me.

查看更多
姐就是有狂的资本
3楼-- · 2019-02-08 08:20

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

查看更多
登录 后发表回答