Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Parent Form + childForm

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@(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

>Solution :

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

Stackblitz Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading