Search code examples
angularangular-forms

Angular Typed Forms - Array of Forms in Form


I want to use strict typing for my form using angular 15.1.0. It contains a list of additional travelers. What i want is something like this:

startForm: FormGroup<StartForm>;
additionalTravelers: FormGroup<TravelerForm>[] = [];

but this does not work. What i now have is this:

additionalTravelers: FormArray<TravelerFormGroup> =
    new FormArray<TravelerFormGroup>([]);

with

export class TravelerFormGroup extends FormGroup {

but with this i can not type the TravelerFormGroup because i get an error here:

<form [formGroup]="travelerForm">

Type 'TravelerFormGroup' is not assignable to type 'FormGroup'. Types of property 'controls' are incompatible. Type 'TravelerMasterForm' is not assignable to type '{ [key: string]: AbstractControl<any, any>; }'. Index signature for type 'string' is missing in type 'TravelerMasterForm'.

Am I on the right pass using FormArray here? How to keep type safety then? I am confused.

Thanks for any advice


Solution

  • Yes FormArray is correct. You should specify like this:

    interface Traveler {
      name: FormControl<string>;
      age: FormControl<number>;
    }
    
    form = new FormGroup({
      additionalTravelers: new FormArray<FormGroup<Traveler>>([]),
    });
    

    The main take-away here is that the types you specify for form controls should themselves be form controls, not just values. For example, if you have a model for a form like this:

    type MyModel = {
      foo: number;
      bars: {
        hello: string;
      }[];
      stuff: string[];
    }
    

    Then you would type the corresponding FormGroup like this:

    type MyModelFormGroup = FormGroup<{
      foo: FormControl<number>;
      bars: FormArray<FormGroup<{
        hello: FormControl<string>;
      }>>;
      stuff: FormArray<FormControl<string>>;
    }>;