Raj Raj - 3 months ago 7
TypeScript Question

Angular 2 - TypeScript: how to hold objects with <Select> control

I am coming from a desktop application background, probably this could be a very basic question for web developers. I am using Angular 2 with TypeScript for a demo application. Following is my code -

<select required [(ngModel)]="model.SelectedSchool">
<option *ngFor="let school of schools" [value]="school">
{{school.Name}}
</option>
</select>


Here "schools" is an array of School object, where School further contains array of other objects like Class[], Teacher[] and some other properties of string and int type.

I need when user select any School in the above code, School object should be assigned to SelectedSchool property in my associated Component for this form.

It works when I assign any string/number type like "SelectedSchoolId" or "SelectedSchoolName" to associated properties of component, but shows target property - "SelectedSchool" as undefined when I want the same with any object.

Am I doing something wrong in the above code, or is it not possible to passback any object type back to component class.

Thanks

Answer

Use ngValue instead of value

<select required [(ngModel)]="model.SelectedSchool">
   <option *ngFor="let school of schools" [ngValue]="school">
     {{school.Name}}
   </option>
</select>

As far as I remember value will work with objects as well with the next update (RC.r) not sure though if I don't mix something up here.

Comments