Fr3ak1n0ut Fr3ak1n0ut - 2 months ago 21
TypeScript Question

How to bind an objects property to a Angular2 form item using select

I have a problem with angular forms.
I am trying to create a form that uses data from a mongo collection and provides it via the

<select>
directive.
I have a FormBuilder that is initialized like this:

ngOnInit() {
this.addForm = this.formBuilder.group({
department_pk: ['', Validators.required],
name_c: ['', Validators.required],
location_fk: [],
expirationdate_d: [],
});
}


The Problem is the
location_fk
property. I am trying to fill the value of this property via the following
<select>
statement (I left the other form groups (for name_c, ...) out of this code snippet):

<form [formGroup]="addForm">
<div class="form-group">
<label>Location (*): </label>
<select class="form-control" formControlName="location_fk" (ngModelChange)="onChange($event)" name="select">
<option [ngValue]="i" *ngFor="let i of locations">{{i.name_c}}</option>
</select>
</div>
</form>


I managed to extract the value of
i
, however, I want to extract a property,
i.location_pk
, from the collection, while still displaying
i.name_c
in the selection that is visible for the user. Is there any way to do this?

Answer

Did you tried this?

<option [ngValue]="i['propName']" *ngFor="let i of locations">{{i.name_c}}</option>

or

<option [ngValue]="i.propName" *ngFor="let i of locations">{{i.name_c}}</option>