1

nested form is possible in reactive form but I don't know how to implement it in dynamic form in angular 2 so is it possible in dynamic forms in angular 2 ?

6
  • 1
    Yes, it's possible. What have you tried so far? Commented Aug 11, 2017 at 13:44
  • 1
    a millions of articles out there around Angular2 dynamic form, just google them Commented Aug 11, 2017 at 13:46
  • I know how to create dynamic forms but I want to create nested form in dynamic form Commented Aug 11, 2017 at 13:48
  • You are maybe looking for formgroups? Commented Aug 11, 2017 at 13:57
  • yes, u r right @ Vega Commented Aug 11, 2017 at 13:58

1 Answer 1

1

Angular's (2.x+) approach to nested forms is not similar to AngularJS (1.x).

In Angular, FormGroups and FormArrays are already letting you create a nested form.

<form [formGroup]="fatherForm">

   <input [formControl]='fatherForm.get('firstName')'>

   <form  [formGroup]="fatherForm.get('childForm')">
       <input [formControl]='fatherForm.get('childForm.aNestedControl')'>
   </form>
</form>

And then in the class :

fatherForm = new FormGroup({

    firstName : new FormControl()

    childForm: new FormGroup({

        aNestedControl : new FormControl()

    })

})

you can even make it cleaner in the html by creating getters:

in the class :

   get childForm(){
       return this.fatherForm.get('childForm')

   }

and then in the html :

<form [formGroup]="fatherForm">

   <input [formControl]='fatherForm.get('firstName')'>

   <form  [formGroup]="childForm">
       <input [formControl]='childForm.get('aNestedControl')'>
   </form>
</form>
Sign up to request clarification or add additional context in comments.

2 Comments

I am confused but I will try and confirm
@Milad I have a problem; on submitting the form, my parent form does not contain the child form's values. If I put a debug point, I can see the child form with all the selected values, but on submission parent form shows empty object. Any idea where the values are getting missed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.