Search code examples
angular2-formsformbuilderform-controlformgroups

Multi nested model driven form angular 2


I'm working with ionic 2 angular 2. I want to know that how to create a multi-nested formgroup in html template.

For example:

this is form group in .ts file

HomeAddress: this.formBuilder.group({
    Address: ['', Validators.required]
    HomeAddressDetail: this.formBuilder.group({
        Country: ['', Validators.required]
        Tel: this.formBuilder.group({
            PhoneNo: ['', Validators.required],
            HomeNo: ['', Validators.required]
        }),
        Email: this.formBuilder.group({
            PrimaryEmail: ['', Validators.required],
            SecondaryEmail: ['', Validators.required]
        })
    })
});

How can I set the HTML template according to this FormGroup.


Solution

  • You can set the HTML template like bellow:

    <form [formGroup]="HomeAddress">
         <div>Address: <input type="text" formControlName="Address"></div>
         <div formGroupName="HomeAddressDetail">
             <div>Country: <input type="text" formControlName="Country"></div>
             <div formGroupName="Tel">
                  Phone No: <input type="text" formControlName="PhoneNo">
                  Home No: <input type="text" formControlName="HomeNo">
             </div>
             <div formGroupName="Email">
                  Primary Email: <input type="text" formControlName="PrimaryEmail">
                  Secondary Email: <input type="text" formControlName="SecondaryEmail">
             </div>
        </div>
    </form>
    

    I dont know the ionic controls, I replied in angular 2. You can use same format in ionic 2. Here is the plunkr https://plnkr.co/edit/SMCAMddPNmEyHuVS0IK8?p=preview