Search code examples
angularforms

Angular (15) Unable to extend a typed FormGroup


I am messing around with typed FormGroup.

I created the following:

export interface CustomFormControls {
  name: FormControl<string|null>
  content: FormControl<string|null>
}

export class CustomForm extends FormGroup<CustomFormControls> {
    constructor() {
        super({
            name: new FormControl('name'),
            content: new FormControl('content'),
        })
    }
}

and then I am trying to use it in a component:

form: CustomForm = new CustomForm()

and in my template:

<form class="Form" [formGroup]="form">

However, I am getting the following error:

Type 'CustomForm' is not assignable to type 'FormGroup<any>'.
  Types of property 'controls' are incompatible.
    Type 'CustomFormControls' is not assignable to type '{ [key: string]: AbstractControl<any, any>; }'.
      Index signature for type 'string' is missing in type 'CustomFormControls'.
         <form class="Form" [formGroup]="form">

I am not sure to understand what I did wrong in there.


Solution

  • Try adding an index signature for a string key

    export interface CustomFormControls {
      name: FormControl<string|null>
      content: FormControl<string|null>
      [key: string]: AbstractControl<any, any>;
    }