Home > Net >  How to use FormArray in Angular 14
How to use FormArray in Angular 14

Time:12-17

I'm creating a dynamic input in a reactive form using Angular 14. I'm getting this error:

error TS7053: Element implicitly has an 'any' type because expression of type '"controls"' can't be used to index type 'AbstractControl<any, any>'. Property 'controls' does not exist on type 'AbstractControl<any, any>'. 270 <div *ngFor="let skill of myDetailsForm.get('skills')['controls']">

And VS code is suggesting this:

Object is possibly 'null'.ngtsc(2531) my-record.component.ts(7, 144): Error occurs in the template of component MyRecordComponent. Element implicitly has an 'any' type because expression of type '"controls"' can't be used to index type 'AbstractControl<any, any>'. Property 'controls' does not exist on type 'AbstractControl<any, any>'.ngtsc(7053)

My code:

<div formArrayName="skills">
    <div *ngFor="let skill of myDetailsForm.get('skills')['controls']; let i=index">
        <input type="text" [formControlName]="i">
    </div>
</div>

this.myDetailsForm = new FormGroup({
    ... // other form independent controls
    skills: new FormArray([new FormControl('')]),
});

Please point out my mistake.

CodePudding user response:

Implement a getter function for returning the skills control as FormArray.

my-record.component.ts

get skills(): FormArray {
  return this.myDetailsForm.get('skills') as FormArray;
}

my-record.component.html

<div *ngFor="let skill of skills['controls']; let i = index">
  <input type="text" [formControlName]="i" />
</div>

Demo @ StackBlitz

  • Related