Home > database >  ERROR Error: Cannot find control with path: 'emails -> 0 -> email'
ERROR Error: Cannot find control with path: 'emails -> 0 -> email'

Time:03-04

I am trying to create a form containing a form of this type:

formGroup

formControl

formControl

formArray

formGroup

formControl

formControl

When I click on the button to add reactive fields and I submit the form after filling, the first field does not contain any data. And i get this error:

ERROR Error: Cannot find control with path: 'emails -> 0 -> email'

and

ERROR Error: Cannot find control with path: 'emails -> 0 -> send'

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent{


  profileForm = this.fb.group({
    firstName: [''],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
    }),
    emails: this.fb.array([''])
  });


  get emails() {
    return this.profileForm.get('emails') as FormArray;
  }

  addEmail() {
    this.emails.push(this.fb.group({
      email:[''],
      send:['']
    }));
  }

  constructor(private fb: FormBuilder){}

  public submit():void{
    console.log(this.profileForm.value);
  }


}

app.component.html

<form [formGroup]="profileForm" (ngSubmit)="submit()">

  <div>
    <label>firstName</label>
    <input type="text" formControlName="firstName">
  </div>

  <div>
    <label>lastName</label>
    <input formControlName="lastName" type="text">
  </div>

  <div formGroupName="address">
    <label>Adresse</label>
    <label>street</label><input formControlName="street" type="text">
    <label>city</label><input formControlName="city" type="text">
    <label>state</label><input formControlName="state" type="text">
  </div>

  <div formArrayName="emails">
    <h2>Aliases</h2>
    <button type="button" (click)="addEmail()">  Add another alias</button>

    <div [formGroupName]="i" *ngFor="let e of emails.controls; let i=index;">
      <div>
        <label>email:</label>
        <input type="text" formControlName="email">
        <input type="checkbox" formControlName="send">

      </div>


    </div>
  </div>

  <button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>

CodePudding user response:

Use

emails: this.fb.array([])

instead of

emails: this.fb.array([''])

Sample Demo on StackBlitz


Reference

Creating an in-place editable table using FormArray

  • Related