FormGroupとFormArrayはいつ使うべきでしょうか? 質問する

FormGroupとFormArrayはいつ使うべきでしょうか? 質問する

フォームグループ:

フォームグループ各子 FormControl の値を、各コントロール名をキーとして 1 つのオブジェクトに集約します。

const form = new FormGroup({
  first: new FormControl('Nancy', Validators.minLength(2)),
  last: new FormControl('Drew')
});

フォーム配列:

フォーム配列各子 FormControl の値を配列に集約します。

const arr = new FormArray([
  new FormControl('Nancy', Validators.minLength(2)),
  new FormControl('Drew')
]);

どちらを優先して使用すべきでしょうか?

ベストアンサー1

FormArray は FormGroup のバリアントです。主な違いは、データが配列としてシリアル化されることです (FormGroup の場合はオブジェクトとしてシリアル化されます)。これは、動的フォームのように、グループ内に存在するコントロールの数がわからない場合に特に便利です。

簡単な例で説明してみましょう。たとえば、ピザの注文を顧客から受け取るフォームがあるとします。そして、特別なリクエストを追加したり削除したりするためのボタンを配置します。コンポーネントの HTML 部分は次のとおりです。

<section>
  <p>Any special requests?</p>
  <ul formArrayName="specialRequests">
    <li *ngFor="let item of orderForm.controls.specialRequests.controls; let i = index">
      <input type="text" formControlName="{{i}}">
      <button type="button" title="Remove Request" (click)="onRemoveSpecialRequest(i)">Remove</button>
    </li>
  </ul>
  <button type="button" (click)="onAddSpecialRequest()">
    Add a Request
  </button>
</section>

特別なリクエストを定義および処理するコンポーネント クラスは次のとおりです。

constructor () {
  this.orderForm = new FormGroup({
    firstName: new FormControl('Nancy', Validators.minLength(2)),
    lastName: new FormControl('Drew'),
    specialRequests: new FormArray([
      new FormControl(null)
    ])
  });
}

onSubmitForm () {
  console.log(this.orderForm.value);
}

onAddSpecialRequest () {
  this.orderForm.controls
  .specialRequests.push(new FormControl(null));
}

onRemoveSpecialRequest (index) {
  this.orderForm.controls['specialRequests'].removeAt(index);
}

FormArray は、FormGroup の「addControl」、「removeControl」、「setValue」などを使用するよりも、「push」、「insert」、「removeAt」を使用して FormControls を操作する方が簡単であるという点で、FormGroup よりも柔軟性があります。FormArray メソッドにより、コントロールがフォームの階層内で適切に追跡されることが保証されます。

お役に立てれば。

おすすめ記事