Getting error Cannot find control with name: '0' in Reactiive Form in Angular 12

Viewed 163

I have created a simple Angular project in Reactive Form in Angular 12

When I add a control clicking button 'Add Mobile No' getting error message 'Cannot find control with name: '0'.

The Component HTML is:

<h3>Reactive Form Example</h3>

<div class="container">

    <div class="row">
        <div class="col-md-12">

            <form [formGroup]="signUpForm" (ngSubmit)="onSubmit()">   
                
                <div>
                    <label>
                        Enter Name:
                    </label>
                    <input type="text" class="form-control" formControlName="abc">
                </div>
                  
                <div fromArrayName="mobiles" *ngFor="let mob of mobiles.controls; let i = index;" >
                       
                            <label>Mobile No:</label>
                            <input type="text"  [formControlName]="i">                          
                        
                </div>                                  

                <div>
                    <button type="button" class="btn btn-success" (click)="addNewMobile()">Add Mobile No:</button>
                </div>                    

                <div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>

            </form>


        </div>
    </div>

</div>

ReactiveFormComponent:

import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.css']
})

export class ReactiveFormComponent  { 

signUpForm: FormGroup

constructor(private formBuilder: FormBuilder) {
this.signUpForm = this.formBuilder.group({
  abc: this.formBuilder.control(''),
  mobiles: this.formBuilder.array([

  ])
});        
}  

ngOnInit() {

} 

onSubmit(){
console.log(this.signUpForm);

}

get mobiles(): FormArray {
return this.signUpForm.controls.mobiles as FormArray;
}
addNewMobile(){
this.mobiles.push(new FormControl(""));
//this.mobiles.push(this.formBuilder.control(''))
//(<FormArray>this.signUpForm.controls['mobiles']).push(this.formBuilder.control(''))
//this.mobiles.push(new FormControl(''));
console.log("AAA");
//this.signUpForm.addControl('', new FormControl());
console.log("BBB");
}

}
           

I am using Angular 12.

2 Answers

There is spelling mistake in your HTML. It should be formArrayName="mobiles" not fromArrayName="mobiles"

You are currently telling Angular to store the values in the index, but you want to capture them in formArray variable. instead of i, you might want to try providing mob in the formControlName, since you are looping.

Related