shou2017.com
JP

Creating a nested form in Angular

Thu Jul 13, 2023
Sat Aug 10, 2024

This is about reactive forms, which are often used in Angular. I created a nested form, so I’m making a note so I don’t forget!

With a nested form, you want to send values like this:

{
  "id": 123,
  "info": {
    "name": "taro",
    "age": 20
  }
}

The method is super simple!

Just create a child group under the parent group.

Creating a nested form group

First, create an instance and do as follows:

// new.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

form!: FormGroup;

@Component({
  selector: 'app-new',
  templateUrl: './new.component.html',
})
export class ProfileEditorComponent {
  // Parent group form
  this.form = new FormGroup({
      id: new FormControl(null, [Validators.required]),
      // Child group info
      info:  new FormGroup({
        name: new FormControl(null, [Validators.required]),
        age: new FormControl(null, [Validators.required]),
      })
  });
}

Since the child group info is nested under the parent group form, the view should be as follows:

<!-- new.component.html -->
<!-- Parent group -->
<form [formGroup]="form" (ngSubmit)="onCreatePost(form.value)">  
  <input formControlName="id">
    <!-- Child group -->
    <div formGroupName="info">
      <input formControlName="name">
      <input formControlName="age">
    </div>
</form>

That’s it!

See Also