Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Update FormGroup nested value?

Tags:

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

like image 318
ismaestro Avatar asked Jan 26 '17 12:01

ismaestro


People also ask

How do I change FormGroup values?

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 do I use FormControl inside FormGroup?

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.

Can we use Formcontrolname without FormGroup?

Formcontrolname Must Be Used With A Parent Formgroup Directive.

What is the difference between FormGroup and FormControl?

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.


1 Answers

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.

like image 67
Karan Garg Avatar answered Sep 21 '22 04:09

Karan Garg