0

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.

1
  • try formMain.get('items')['controls'] Commented Jul 26, 2022 at 1:54

1 Answer 1

1

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">
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.