I have the following FormGroup
definitions:
readonly firstGroup = new FormGroup({
account: new FormControl('', { nonNullable: true }),
password: new FormControl('', { nonNullable: true })
});
readonly secondGroup = new FormGroup({
account: new FormControl('', { nonNullable: true }),
password: new FormControl('', { nonNullable: true })
});
readonly control = new FormControl<boolean>(false);
readonly group = new FormGroup({
control: this.control,
first: this.firstGroup
second: this.secondGroup
});
I’ve defined the FormGroup
s separately to make them easier to manipulate within the component.
Within the component I use the value
property of the FormGroup
(AbstractControl
actually) to get all of the FormGroup
s values (those that aren’t disabled of course) but when using said property all I get back is the value for the single control
FormControl
value.
const values = this.group.value;
console.log(values); // Prints { control: false }
This is unexpected, I thought I would receive the following object:
{
control: false,
first: {
username: '',
password: '',
},
second: {
username: '',
password: '',
}
}
Note that none of the controls are disabled!
Now, if I instead define my FormGroup
in the following way:
readonly control = new FormControl<boolean>(false);
readonly group = new FormGroup({
control: this.control,
first: new FormGroup({
account: new FormControl('', { nonNullable: true }),
password: new FormControl('', { nonNullable: true })
})
second: new FormGroup({
account: new FormControl('', { nonNullable: true }),
password: new FormControl('', { nonNullable: true })
})
});
Then I receive the object I was expecting when calling the value
property.
{
control: false,
first: {
username: '',
password: '',
},
second: {
username: '',
password: '',
}
}
I’m confused as to why this is happening.
I’m intentionally using the value
getter so that disabled controls are not included in the result.
Is anyone able to shed some light on what’s going on?
Why does the value
property return two different objects based on how I’ve defined the form?
3