Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 214
user984200 Avatar asked May 07 '26 21:05

user984200


1 Answers

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>>;
}>;
like image 123
Mike Jerred Avatar answered May 11 '26 17:05

Mike Jerred



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!