Search code examples
angulartypescriptformarray

(Angular 5) Error: control.registerOnChange is not a function


I need to show the values in a form to edit later. always show me this error "ERROR Error: control.registerOnChange is not a function"

I build my form in this way

 form = this._fb.group({
  createdAt:'',
  customer: this._fb.group({
    name: '',
    lastname: '',
    phone: '',
    address: ''
  }),
  purchases: this._fb.array([ <-- this is the problematic,the others work well
    this._fb.group({
      product: this._fb.group({
        name:'',
        location:'',
        categoryS:'',
        price:''
      }),
      quantity: ''
    })
  ])      
});

and try to show it

   <div formArrayName="purchases">
        <label>Products:</label> 
     <div *ngFor="let product of form.controls.purchases.controls; let i = index">
         <input [formControlName]="i" class="form-control"/>            
      </div>
     </div>

any ideas?

View in StackBlitz


Solution

  • I can share my idea.

    Change template as follows:

    <div *ngFor="let product of form.controls.purchases.controls; let i = index" [formGroupName]="i">
      <div formGroupName="product">
        <input formControlName="name" class="form-control"/>  
        <input formControlName="location" class="form-control"/>     
        ...
      </div>
    </div>
    

    And also make sure you correctly fill purchases array on edit action:

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

    Check also forked Stackblitz Example