Hey there! I'm fairly new to Angular 2 and have been trying to tackle this issue for a while now. I have a user object that contains another nested object, defined by the User interface:
export interface UserModel{
name: string,
service: Service
}
I've got an array of services and a form for creating a 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>
I'm struggling with how to pass the selected service object to the User object. When I try it this way, I end up with:
Object{
"name": "something",
"service": "[Object object]"
}
It's clear that passing an object as the value to the select element doesn't work. So, I decided to set the value to the id of the Service instead and modified the interface:
export interface UserModel{
name: string,
serviceId: number
}
Prior to submission, I find the Service object based on its id in the array of services and set it in the User object along with the Service object inside.
userModel: UserModel;
user: User;
submit(model: UserModel ){
this.user = {
name : model.name,
service: this.findService(model.serviceId)
}
}
ngOnInti(){
this.userModel= <userModel>{};
}
Does this approach seem effective? Are there better ways to handle this situation? This is just a snippet of (handwritten) code that represents a working example. Thanks!