Home > Back-end >  FormArray values getting null Error: Cannot find control with name '0'
FormArray values getting null Error: Cannot find control with name '0'

Time:10-17

I am not able to get the FormArray field Values while submitting the form. I am getting empty values in Form Array Fields.

Whenever Iam clicking on addHobbies button iam getting an error: Cannot find control with name '0'

signupForm.component.html

<div >
    <form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
        <div >
            <div >
            <label>Email</label>
            <input type="email" formControlName="email" >
            <span >Email Required</span>
            </div>
        </div>
        <div FormArrayName="hobbies">
            <div >
                <div >
                <button type="button"  (click)="addHobbies()">Add Hobbies</button>
                </div>
            </div>
            <div >
                <div  *ngFor="let hobby of hobbyControls.controls; let i=index">
                {{i}}
                <input type="text"  [formControlName]="i">
                </div>
            </div>
        </div>
        <div >
        <button type="submit" >Submit</button>
        <button type="reset" >Reset</button>
        </div>
    </form>
</div>

signupform.component.ts

export class ReactiveformsComponent implements OnInit {
    
  signupForm : FormGroup;
 
  constructor(private fb: FormBuilder) { }

  
     ngOnInit(): void {

        this.signupForm = this.fb.group({
            'email': [''],
            'hobbies': this.fb.array([])
        })

    }
    addHobbies(){
        //const hobbyControl = this FormControl('');
        (<FormArray>this.signupForm.get('hobbies')).push(this.fb.control(''));
    }
    get hobbyControls(){
        return this.signupForm.get('hobbies') as FormArray;
    }

    onSubmit(){
        console.log(this.signupForm.value);
    }

output

{"email":"[email protected]","hobbies":["",""]}

CodePudding user response:

Try it like this, instead of i use hobby here

<div >
                <div  *ngFor="let hobby of hobbyControls.controls; let i=index">
                {{i}}
                <input type="text"  [formControlName]="hobby">
                </div>
            </div>

CodePudding user response:

There is a typo error for FormArrayName.

<div FormArrayName="hobbies">
  ...
</div>

Solution

Change it to formArrayName so the directive will work.

<div formArrayName="hobbies">
  ...
</div>

Sample Solution on StackBlitz


References

Angular Form Array

  • Related