Felipe Fernandes
Felipe Fernandes

Reputation: 103

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?

Upvotes: 10

Views: 6581

Answers (1)

developer033
developer033

Reputation: 24864

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}});

Upvotes: 18

Related Questions