Search code examples
angulartypescriptangular5angular2-formbuilder

(Angular 5) Error: Cannot find form control with name:


I'm trying to edit a form and when I want to show the values to edit, using setValue I get an error "ERROR Error: Cannot find form control with name: purchases."

component.ts

ngOnInit() {
  this.form = new FormGroup({
      customer: new FormGroup({
        name: new FormControl(),
        lastname: new FormControl(),
        address: new FormControl(),
        phone: new FormControl()
      }),
      createdAt: new FormControl(),
      purchases: new FormArray([])
  });
}

my function to edit

onEdit(invoice) {    
  this.form.setValue(invoice)   
}

component.html

<div class="col-md-8">
    <div formGroupName="customer">
      <h3>Customer</h3>
      <label>Name: <input class="form-control" type="text" formControlName="name"> </label>
      <label>Last Name:<input class="form-control" type="text" formControlName="lastname"></label>
      <label>Phone:<input class="form-control" type="text" formControlName="phone"></label>
      <label>Address:<input class="form-control" type="text" formControlName="address"></label>
   </div>
   <div><li formArrayName="purchases"></li></div>
</div>

View in StackBlitz

values in console

console


Solution

  • The error is caused by calling setValue(), because it performs strict checks.

    You are trying to assign an array of multiple items to FormArray having only one initial FormGroup at index 0.

    Assigning value at index 1 fails, as it does not exist.

    Steps to solve it:

    1. Define the form array:

      purchases: new FormArray([
          new FormGroup({
              product: new FormGroup({
                  categoryS: new FormControl(''),
                  location: new FormControl(''),
                  name: new FormControl(''),
                  price: new FormControl('')
              }),
              quantity: new FormControl('')
          })
      ])
      
    2. Use patchValue

    3. Clear the form array:

      while (purchasesFormArray.length) {
         purchasesFormArray.removeAt(0);
      }
      
    4. Populate the form array in a loop

      invoice.purchases.forEach(purchase => {
          purchasesFormArray.push(this._fb.group(purchase));
      });  
      

    Fixed code is here: View in StackBlitz.