shou.com
JP / EN

Angularでネストしたフォームをつくる

Thu Jul 13, 2023
Thu Jul 13, 2023

Angularでよく使うリアクティブフォームですが、ネストしたフォームを作ったので、忘れないようにメモしておきます!

ネストしたフォームで、こういう値を送りたい。

1
2
3
4
5
6
7
{
  "id": 123,
  "info": {
    "name": "taro",
    "age": 20
  }
}

やり方はすごく簡単!。

親グループの配下に子グループを作ってやればいいだけ。

ネストしたフォームグループの作成

まずはインスタンスを作成し、以下のようにします。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// newc.omponent.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 {
  // 親グループ form
  this.form = new FormGroup({
      id: new FormControl(null, [Validators.required]),
      // 子グループ info
      info:  new FormGroup({
        name: new FormControl(null, [Validators.required]),
        age: new FormControl(null, [Validators.required]),
      })
  });
}

親グループであるformの下に子グループであるinfoをネストさせていますので、ビューは以下のようにします。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!-- new.component.html -->
<!-- 親グループ -->
<form [formGroup]="form" (ngSubmit)="onCreatePost(form.value)">  
  <input formControlName="id">
    <!-- 子グループ -->
    <div formGroupName="info">
      <input formControlName="name">
      <input formControlName="age">
    </div>
</form>

これで完成!

See Also