i got a question i havent found an answer too and i was curious if one of you came across this.
Imagine having a ParentForm and a ChildForm. Child and Parent are each one Angular Component.
parentForm: FormControl = new FormBuilder.group({})
childForm: FormControl = new FormBuilder.group({
checkbox: false,
})
now if i want to add the childForm to the parentForm to connect them, i would do:
@(ViewChild)(ChildComponent) = childComponent;
ngAfterViewInit(): {
this.parentForm.addControl('childFormName', this.childComponent.childForm)
}
This whole action would make the ParentForm look like this:
parentForm: {
childFormName: {
checkbox: false
}
}
I dont want this, i would like to not have to give the added form an extra name, and would want to have it look like this:
parentForm: {
checkbox: false
}
Has anyone every ecountered a usecase for this?
thanks for the help in advance
First I would clone the child form, since I do not want the updates on the child form to propagate to the parent. Then simply using object de-structuring add the controls to the parent form.
I am using cloneDeep
from lodash
for cloning since its the most reliable method to create a deep clone ( my preference ).
ngOnInit() {
const cloneChildForm = cloneDeep(this.childForm);
this.parentForm = this.fb.group({
...this.parentForm.controls,
...cloneChildForm.controls,
});
console.log(this.parentForm);
}