(Angular 5) Error: Cannot read property 'setValue' of undefined

16.7k Views Asked by At

I'm initializing my form this way, but when I need to edit it, it does not accept the values

component.ts

ngOnInit() {
  this.tinvoiceService.initForm();
}

tinvoice.service.ts

form: FormGroup;

constructor(
  private _fb: FormBuilder, 
  private invoiceService: InvoiceService
) {}

initForm(): void {
  this.form = this._fb.group({
    customer: [null, Validators.required],
    totalPrice: 0,
    purchases: this._fb.array([])
  });

  // initialize stream
  const myFormValueChanges$ = this.form.controls['purchases'].valueChanges;
  myFormValueChanges$.subscribe(purchases => this.updatePurchasesAmount(purchases));

}

from the HTML I pass the values

tinvoice.component.html

<a 
  class="btn btn-outline-info text-info" 
  (click)="tinvoiceService.populateForm(invoice)">
  Edit
</a>

tinvoice-list.component.ts

populateForm(invoice) {
  this.form.setValue(invoice);  
}

by console I have this result

enter image description here

View in StackBlitz

any ideas?

2

There are 2 best solutions below

0
On

Old Question but will give my view

When a user clicks on the edit button, the console logs works indicates

Cannot find form control with name: purchases

So we start from here and identify the issue in the line

  this.form.setValue(invoice) 

If we log the value of invoice at this point we see

{
    "createdAt": "Mon May 10 2021 15:32:51 GMT+0100 (UTC+01:00)",
    "customer": {
        "address": "s",
        "lastname": "Perez",
        "name": "Carlos ",
        "phone": "7861236589"
    },
    "purchases": [
        {
            "product": {
                "categoryS": "-MZyCBHUjLrfxzoRdZBM",
                "location": "Store",
                "name": "TV Samsung",
                "price": 50
            },
            "quantity": 1
        }
    ],
    "totalPrice": 50,
    "$key": "-M_LgTlysUg07lHdjtuG"
}

If we log value of this.form.value we aee

{
    "customer": {
        "name": null,
        "lastname": null,
        "address": null,
        "phone": null
    },
    "createdAt": null
}

So you are trying to assign the form an incorrect structure of the object.

To check that your code is actually working you can simply change setValue to patchValue. Below solutions works as patchValue will only look for form controls that only exists unlike setValue. To use setValue on the other hand you will have to ensure that all the properties in your object are represented in the FormGroup, otherwise remove those properties from the object

Below is a Demo showing a solution by changing setValue to patchValue

2
On

Form is a UI element, it gets instantiated after view is rendered.

you can try calling this function in ngAfterViewInit, the error should be gone. if not just create one fiddle and I will try to fix it for you.