angulartypescripttypesformarrayformgroups

How to correctly use types with FormArray in Angular


How should I declare this type ?

Let say I've a FormGroup

  1. I instantize it in the constructor.
export interface MyType {
 myValue: string
}
myForm: FormGroup
myArray: FormArray // <FormControl<MyType>>

constructor(private _formBuilder: FormBuilder) {
  myForm = new FormGroup({
    myArray: this._formBuilder.array([])
  })
}
  1. Because I have somewhere a button that let me add a new element to the array, I do as follow
addElement() {
  this.myArray = this.myForm.get('myArray') as unknown as FormArray

  this.myArray.push(this.newElement())
}

private _newElement(): FormGroup { // What type to use ? 
  return this._formBuilder.group({
     myValue: ''
  })
}

But when I do use the

myArray: FormArray<FormControl<MyType>>

I get the following error

Argument of type 'FormGroup<any>' is not assignable to parameter of type 'FormControl<MyType>'.
  Type 'FormGroup<any>' is missing the following properties from type 'FormControl<MyType>': defaultValue, registerOnChange, registerOnDisabledChange

Somebody knows


Solution

    1. Declare the interface/class for the Typed Form.
    export class MyTypeForm {
      myValue: FormControl<string>;
    }
    
    1. Declare myArray type as FormArray<FormGroup<MyTypeForm>>.
    myArray: FormArray<FormGroup<MyTypeForm>>;
    
    1. The _newElement method to return FormGroup<MyTypeForm> type.
    private _newElement(): FormGroup<MyTypeForm> {
      return this._formBuilder.group<MyTypeForm>({
        myValue: this._formBuilder.control(''),
      });
    }
    

    Demo @ StackBlitz

    Reference: Angular Strictly Typed Forms (Complete Guide)