I am working on an Angular component that manages a list of FormGroups. This list can be expanded and items can be deleted. But I also want the component to handle any kind of FormGroup. So for example, the FormGroup can contain 1 FormControl like so:
interface TestForm { color: FormControl<string | null>; } But it should also be able to handle a FormGroup with multiple FormControls, like this:
interface TestForm { color: FormControl<string | null>; nickName: FormControl<string | null>; hasPet: FormControl<boolean | null>; } Additionally, I want the component to handle a TemplateRef defined in the parent, which should contain all the form elements like so:
<ng-template #itemTemplate let-item="item"> <input type="text" [formControl]="item.controls.color" /> </ng-template> I created an example here of what it should look like: https://stackblitz.com/edit/nuurvgjk?file=src%2Fapp%2Feditable-list.component.ts
So in this example I use form elements because I know what the interface of the FormGroup looks like, but this should be dynamic and declared in an <ng-template> outside of this component. I got this working locally, but I consider it less relevant for the goal that I want to achieve.
I have played around with giving the FormGroup and the component a generic <T> type and tried to create a new FormGroup using the generic type. But I haven't found a way yet to actually do it.
I was hoping there was a way to do something like this:
interface SmallForm { a: number; b: string; } const formGroups: FormGroup<SmallForm>[] = [ new FormGroup({ a: new FormControl(2), b: new FormControl('test') }), new FormGroup({ a: new FormControl(11), b: new FormControl('hello') }) ]; const newFormGroup = new FormGroup<SmallForm>(); formGroups.push(newFormGroup); Maybe there is no way to set up a new FormGroup without knowing the interface beforehand, but I really want to find a conclusive answer.
UntypedFormGroup?