Angular: How do I deal with nested FormGroups in the HMLT Template?

Viewed 34

I'm very new to Angular and trying to build a form to collect user information.

Let's say I have a user that can have a "friend" associated with them. A simplified version of my FormGroup looks like this:

userInformation = new FormGroup({
   name: new FormControl('', [Validators.required]),
   age: new FormControl('', [Validators.required]),
   friend: new FormGroup({
      name: new FormControl('', [Validators.required]),
      age: new FormControl('', [Validators.required])
   })
})

In my HTML, I have:

<form [formGroup]="userInformation" (ngSubmit)="onSubmit">
    <input type="text" placeholder="full name">
    <input type="text" placeholder="full name">
    <input type="text" placeholder="full name">
    <input type="text" placeholder="full name">
</form>

How do I bind the first two inputs to the userInformation and the second two inputs to the userInformation.friend?

1 Answers

For nested formgroups we use formgroupName, so all you need to create is a container, where you set the formGroupName and the "friend" form controls inside it:

<form [formGroup]="userInformation">
  <input type="text" formControlName="name" placeholder="name" />
  <input type="text" formControlName="age" placeholder="age" />
  <ng-container formGroupName="friend">
  <!-- ^^^^^^^^^HERE^^^^^^^^^^^^^^^^-->
    <input type="text" formControlName="name" placeholder="name" />
    <input type="text" formControlName="age" placeholder="age" />
  </ng-container>
</form>
Related