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

Rafael Corzo picture Rafael Corzo · Sep 22, 2018 · Viewed 12.8k times · Source

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?

Answer

MehulJoshi picture MehulJoshi · Sep 22, 2018

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.