I would like to ask if it is possible to send a whole object to the reactive form in angular 2.
This is my form:
this.parameterForm = this.fb.group({
'name': ['', Validators.required],
'description': "",
'parameterType':''
});
The third attribute (parameterType) should be a object. (The name and description are only plain strings.
My HTML for the parameterType is(formControlName is used to map it):
<label for="parameterType">Parameter Type</label>
<select id="parameterType" class="form-control" formControlName="parameterType">
<option *ngFor="let parameterType of parameterTypes" [value]="parameterType">
{{parameterType.name}}
</option>
</select>
The values in the select are objects (which are created elsewhere). When submitting the form, I would like to have the parameterType object. The submit is trying to parse the form to a object called Parameter:
export class Parameter {
public id: number;
public name: string;
public description: string;
public parameterType? : ParameterType
}
But when im trying to read the result in the console, the parameterType contains just a string "[Object object]", which looks like the parameterType is just a String and when submitting the form, the object is converted to a simple string.
My submit function is like this:
onSubmit( {parameter}:{parameter: Parameter} ) {
console.log(parameter);
}
Now im just doing it so, that into parameterType im sending the id and through a service I get the object but this solution is not very nice. Do you know any way i could pass the object to the form?
Thanks
I think you need to use [ngValue] instead of [value].
You have several options :
Let's say I have the following form :
user: FormGroup;
this.user = this.formBuilder.group({
account: this.formBuilder.group({
email: ['', [Validators.required, Validators.pattern(EmailRegex)]],
password: ['', Validators.required],
passwordConfirm: ['', Validators.required]
}, { validator: this.matchingPasswords('password', 'passwordConfirm') })
});
From there, you can set values of your form with an Object :
let user: SignUp = {
account: {
email: this.mail,
password: '',
passwordConfirm: ''
}
};
this.user.setValue(user);
Where Signup is an interface :
export interface SignUp {
account: {
email: string;
password: string;
passwordConfirm: string;
}
}
You can this way create a new Object from your form :
let jsonResult = {
email: this.user.value.account.email,
password: this.user.value.account.password
};
or use the form as an Object from an interface (with @Output for example) :
@Output() randomOutput= new EventEmitter<SignUp>();
let data: SignUp = Object.assign({}, this.user.value);
this.randomOutput.emit(data);