Search code examples
angularangular-reactive-formsangular4-forms

Fix Reading Value From Another Row in Reactive Forms In Angular


How can i fix this change that is returned? Change is Amount To Pay - Total Amount. The problem is that it doesn't change after i rate and quantity. It only change the value after i change something in the Amount To Pay input? Here's the plunker that I've made.

PLUNKER CODES HERE

onChanges(): void {
  this.invoiceForm.get('amount').valueChanges.subscribe(val => {
    return this.change = this.invoiceForm.get('amount').value - this.invoiceForm.get('summed').value
  });
}

Solution

  • What you're currently doing is sort of mixing template driven forms and reactive forms, by trying to attach an [ngModel] input to your form control. What you want to do is set the value of that form control using the reactive forms API, specifically the .setValue() method. This allows you to update the value of your form control from the component class.

    I've forked your plunkr and updated it with the working code: http://plnkr.co/edit/WqkJpzgdGakHjM2Mnk59?p=preview

    I'll provide the important stuff here for reference:

    this.invoiceForm.get('itemRows').valueChanges.subscribe(values => {
        this.invoiceForm.get('summed')
          .setValue(values.reduce((acc, cur) => acc + cur.itemamt, 0));
    });
    
    this.invoiceForm.get('summed').valueChanges.subscribe(value => {
      this.setChange();
    });
    
    this.invoiceForm.get('amount').valueChanges.subscribe(() => {
      this.setChange();
    });
    

    Then define a setChange method as:

    setChange(): void {
      const change = this.invoiceForm.get('amount').value - 
                     this.invoiceForm.get('summed').value;
      this.invoiceForm.get('change').setValue(change);
    } 
    

    Learn more about reactive forms here: https://angular.io/guide/reactive-forms.