I have this inside a component:
private formBuilder: FormBuilder
...
signupForm: FormGroup;
...
this.signupForm = this.formBuilder.group({
'name': [null, Validators.required],
'account': this.formBuilder.group({
'email': [null, [Validators.required, ...]],
'confirm_email': [null, Validators.required],
}, {validator: ValidationService.emailMatcher}),
'password': [null, [Validators.required,...]]
});
And I want to set the value for the email field. I tried this, but no luck:
this.signupForm.patchValue({'email': '[email protected]'});
But the value is nested, so whats the sintax in this case? I also tried:
this.signupForm.patchValue({'account.email': '[email protected]'});
Also searched here:
https://angular.io/docs/ts/latest/api/forms/index/FormGroup-class.html#!#patchValue-anchor
Thanks
We use the SetValue to update the FormControl , FormGroup or FormArray . When we use it to update the FormGroup or FormArray the SetValue requires that the object must match the structure of the FormGroup or FormArray exactly. Otherwise, it will result in an error.
How to add a FormControl to a FormGroup. To add, update, or remove controls in FormGroup , use the following commands: addControl() adds a control and updates its value and validity. removeControl() removes a control.
Formcontrolname Must Be Used With A Parent Formgroup Directive.
formControl: When you have very few (maybe one or two) independent field on your UI design, maybe an input. So there is no need for a form tag. formGroup: When you have a form that has multiple inputs, dropdown, radio buttons. All of which you want to create a JSON object to pass in API.
Try this:
this.signupForm.patchValue({account:{email: '[email protected]'}});
Another solution is:
(<FormGroup>this.signupForm.controls['account']).controls['email'].patchValue('[email protected]');
Sorry for bad indentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With