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?
This directive is used by itself or as part of a larger form. Use the ngModel selector to activate it. It accepts a domain model as an optional Input . If you have a one-way binding to ngModel with [] syntax, changing the domain model's value in the component class sets the value in the view.
To bind select element to object in angular use [ngValue] property. We will go through an example to understand it further. we will create a component called BindSelectToObjectComponent in our angular project. I created an interface object called language which has id and name properties.
Use the ngModel selector to activate it. It accepts the domain model as an optional Input if you have a one-way binding to ngModel with the [] syntax; changing a value of the domain model in the component class sets a value in the view.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With