I have a reactive form, something like this:
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({
test1: new FormControl(''),
...
}),
});
I want to remove the nested formGroup or at least make it empty, something like this:
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
I tried patchValue({})
, setValue({})
and this.profileForm.removeControl('address')
.
I got no error but the formgroup is not deleted.
CodePudding user response:
There are two possible ways to get your desired result:
- Use
profileForm.get('address').reset()
. This will reset the form to default values. - Delete the address yourself after getting it with
.value
:
const profile = this.profileForm.value;
delete profile.address;
CodePudding user response:
After this.profileForm.removeControl('address');
is necessary to use this.profileForm.updateValueAndValidty();
CodePudding user response:
Taking into account your comment:
I need to sent to api the form group, but sometimes I need to send the the formgroup Address and sometimes I need to send it empty or not to send it at all
I would say that removing part of the from the form group completely, while it should work, might not be the best solution, as it is a destructive operation that will impact the behavior of your form should you want to reuse it after the API call.
A better solution might be to copy the form value and edit it before sending:
const valueToSend = {...this.profileForm.value};
delete valueToSend['address'];
You can see this working on StackBlitz. Switch to "Profile Editor" and see two buttons: "Remove control and send" and "Copy and send", and observe DevTools console.
CodePudding user response:
use
profileForm.removeControl('address')
i tested this using form group builder