Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the value of a nested formBuilder group

My nested form is currently formatted in this way:

ngOnInit() {
  this.user = this.fb.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    quest1: ['', Validators.required],
    account: this.fb.group({
      email: ['', Validators.required],
      confirm: ['', Validators.required]
    }),
    questions: this.fb.group({
        quest2: ['', Validators.required],
    }),
  });
}

I would usually set the value like this:

this.user.controls['quest1'].setValue('false');

But because the formGroups are nested, I'm not sure how to set the nested values.

How do I set a value for "quest2"? What's the correct syntax for set a form control value in a nested formGroup?

like image 289
Felipe Fernandes Avatar asked Jun 15 '17 02:06

Felipe Fernandes


1 Answers

You can do it using the syntax below:

this.user.get('questions.quest2').setValue(false);

Note that setValue method throws an error if some control is missing. So, if you don't want to update all controls, you can use patchValue:

this.user.get('questions.quest2').patchValue(false);

or

this.user.get(['questions', 'quest2']).patchValue(false);

or

this.user.patchValue({questions: {quest2: false}});
like image 155
developer033 Avatar answered Oct 05 '22 23:10

developer033