given this form declaration:
reactiveForm = new FormGroup({
firstname: new FormControl(),
lastname: new FormControl(),
email: new FormControl(),
gender: new FormControl(),
isMarried: new FormControl(),
country: new FormControl(),
address: new FormGroup({
city: new FormControl(),
street: new FormControl(),
pincode: new FormControl(),
}),
});
As we know, we can alter the control values via setValue
or patchValue
. If we use setValue
, we have to provide a value for all controls. If we use patchValue
, we have to provide only values for a subset of controls (for which we want to modify the values).
F. e. in the above case we can use this:
patchName() {
let contact = {
firstname: 'Rahul',
lastname: 'Dravid',
};
this.reactiveForm.patchValue(contact);
}
It works fine.
Now, if I want to patch city
and street
within address
and use this:
patchAddress() {
let address = {
city: 'Bangalore',
street: 'Brigade Road',
};
this.reactiveForm.get('address')?.patchValue(address);
}
I get the error Property 'pincode' is missing in type '{ city: string; street: string; }' but required in type '{ city: any; street: any; pincode: any; }'
.
But if I use it like this:
this.reactiveForm.patchValue({ address: address });
It works.
So, the question is, why in this case patchValue
does require all the three properties provided?
I assume, because with get
I get the strictly typed address
formgroup with three properties and in this case I have to provide all the three properties in patchValue
, regardless the fact, that patchValue
can be used for partial updates.
You can "cast" as formGroup, but really I feel that it's a bug
(this.reactiveForm.get('address') as FormGroup)?.patchValue(address)