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