dev_in_progress dev_in_progress - 2 months ago 16
TypeScript Question

Angular 2 : Template driven form, pass object from selected element to submitting object

Hello I am new to Angular 2 and I'm searching for a good way to solve this from some time. So I have user object that contains another object inside. That user is an interface :

export interface userModel{
name: string,
service: Service
}


Got an array of services and form for creating new User.

<form #f="ngForm" (submit)="addUser(f.value,f.valid)">
<label for="name" class="col-sm-1 control-label">Name</label>
<div class="col-sm-4">
<input class="form-control" [(ngModel)]="userModel.name" #name="ngModel" name="name" ng-maxlength="49" />
</div>
<label class="col-sm-1 control-label">Service</label>
<select class="form-control" name="service" [(ngModel)]="userModel.service">
<option *ngFor='let service of services' [value]='service'>{{service.name}}</option>
</select>
</div>
<button class="btn btn-primary" type="submit">Create</button>
</form>


How can i pass selected service object to User object? When i fill it this way i get:

Object{
"name": "something",
"service": "[Object object]"
}


So obviously i can't pass object as value to select element.
Then i setted that value to id of Service instead.
Modified interface:

export interface UserModel{
name: string,
serviceId: number
}


And before submission i find Service object by that id in array of services and set it in User object with Service object inside.

userModel: UserModel;
user: User;

submit(model: UserModel ){
this.user = {
name : model.name,
service: this.findService(model.serviceId)
}
}



ngOnInti(){
this.userModel= <userModel>{};
}


Is this ok ? Is there better way to manage this? This is working example and just part of (handwriten) code. Thanks

Answer

It stored [Object object] because you have value attribute which do stringify the object. As you wanted to store Object value on option selection, you should use [ngValue] instead of [value]. Basically [ngValue] property persist & keep object value happy.

Markup

<select class="form-control" name="service" [(ngModel)]="userModel.service">
  <option *ngFor='let service of services' [ngValue]='service'>
     {{service.name}}
  </option>
</select>