1

I've been running into a problem trying to get an Angular FormArray, which is nested inside a FormGroup, to take on a value of either an array or null when strict type checking is enabled.

I encountered this problem trying to create a FormGroup that mirrors a standard TypeScript object. All of my standard object fields can be either a value (string, bool, etc.), null, or undefined and I would like a FormGroup that is able to take on the same values. This FormGroup can also have other similar objects nested inside it such as a nested object or array of objects. To mirror this, I created a FormGroup with a nested FormGroup or nested FormArray. The FormGroup typing works perfectly for any FormControls or FormGroups inside the parent FormGroup but I am unable to get the typing to succeed for the FormArray since the FormArray cannot take on a value of null.

Here is a StackBlitz with example code: https://stackblitz.com/edit/angular-typed-formgroup?file=src/app/app.component.ts&view=editor

Here are the models for reference:

interface Parent {
  childField?: string | null;
  childObject?: Child | null;
  childList?: Child[] | null;
}

interface Child {
  field?: string | null;
}

Here are the FormGroup types for reference:

interface ParentForm {
  childField?: FormControl<string | null>;
  childObject?: FormGroup<ChildForm | null>;
  childList?: FormArray<FormGroup<ChildForm | null>>;
  // childList?: FormArray<FormGroup<ChildForm | null> | null>; // TypeScript throws error.
}

interface ChildForm {
  field?: FormControl<string | null>;
}

I was able to get the nested FormGroups to accept null by making the nested FormGroups of type FormGroup<ChildForm | null>. I expected that I would be able to do the same with the nested FormArray by using a type of FormArray<FormGroup<ChildForm | null> | null> or something similar, but I have been unable to get the typing to the point where it will accept a null value when calling form.patchValue({childList: null}).

1
  • Great first question! Commented Jan 6, 2023 at 18:08

1 Answer 1

0

As i know, you could not set "null" for Form Controls.

interface ParentForm {
  childList?: FormArray<FormGroup<ChildForm | null>> | never;
}

And pathValue like this fixed the problem:

form.patchValue({
  childField: null,
  childObject: null,
  childList: [],
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.