angular-reactive-formsangular-formsangular-formbuilder

Getting error while using Angular Form Array


Why am I getting this error, and how to get it fixed: TS2740: Type 'AbstractControl<any, any>' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 2 more.

At this point it is giving error in my html: enter image description here

my html:

<button type="button" (click)="addName()">Add Name</button>

<div formArrayName="names">
    <div *ngFor="let nm of getNames.controls">
        <div [formGroup]="nm"> //THIS LINE IS GIVING ERROR
            <input formControlName="fname" type="text" placeholder="First Name">
            <input formControlName="lname" type="text" placeholder="Last Name">
        </div>
    </div>
</div> 

<div>
    <button type="submit">Submit</button>
</div>

my ts:

export class TestComponent implements OnInit {     
    constructor(private fb: FormBuilder) { }

    form = this.fb.group({
        names: this.fb.array([])
    });

    get getNames(){
        return this.form.controls["names"] as FormArray;
    }

    addName(){
        const newName = this.fb.group({
            fname: ['', Validators.required],
            lname: ['', Validators.required]
        });
        this.getNames.push(newName);
    }

    onSubmit():void{
        console.log(this.form.value)
    }

   ngOnInit(): void {

   }

}

Solution

  • I got it resolved by using $any in html as below.

    <div *ngFor="let nm of  $any(getName).controls; let i=index">