This is how I define my form:
constructor(private fb: FormBuilder) {}
formMain = this.fb.group({
title: ['', Validators.required],
description: ['', Validators.required],
currency: ['USD'],
items: new FormArray([]),
});
I would like to loop through items
.
<form [formGroup]="formMain">
<button (click)="addField()">Add Fields</button>
<div formArrayName="items">
<ng-container *ngFor="let item of formMain.get('items')?.controls">
<input type="text" [formControl]="item" value="foo">
</ng-container>
</div>
</form>
Well, when I try this, I get the error
Property 'controls' does not exist on type 'AbstractControl'.
How can I fix this? I am using Angular 13.3.0.
CodePudding user response:
Angular definition for formMain.get('items')
is as below. It does not know what actual type (FormControl
or FormArray
or FormGroup
) is.
get(path: Array<string | number> | string): AbstractControl | null;
You have to define a method that return type is assumed as FormArray
.
getItems = (): FormArray => {
return this.formMain.get('items') as FormArray;
}
Then your template will be like this.
<ng-container *ngFor="let item of getItems().controls">