Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting object properties via ngModel select list in Angular 2?

Tags:

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?

like image 960
marked-down Avatar asked Jun 07 '16 01:06

marked-down


People also ask

How does ngModel work in angular 2?

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.

How do I select objects to bind?

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.

How do you input ngModel?

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.


1 Answers

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

like image 131
Günter Zöchbauer Avatar answered Oct 13 '22 00:10

Günter Zöchbauer