0

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
  });
}
Joseph
  • 7,042
  • 23
  • 83
  • 181

1 Answers1

1

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.

vince
  • 7,808
  • 3
  • 34
  • 41
  • I think you should also use valueChanges in the itemRows since if you change something in the rate or quantity, it will affect the total. Can you edit your code? Thanks – Joseph Jan 23 '18 at 14:00
  • Did you get what i mean? – Joseph Jan 23 '18 at 14:17
  • By the way what happens when you mix template driven and reactive forms? – Joseph Jan 24 '18 at 00:45
  • You're welcome :) I know there are pros and cons to either/or and mixing them in the same form isn't good practice. May make for a separate question. Lots of resources talking about differences (here's a good link: https://stackoverflow.com/questions/39142616/what-are-the-practical-differences-between-template-driven-and-reactive-forms) but not too many talking about mixing the two. I guess the main thing would be that reactive is syncronous while template-driven is asynchronous in nature. Mixing async + sync = Zalgo. Avoid zalgo at all costs – vince Jan 24 '18 at 03:02