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
  });
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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
Did you get what i mean?
By the way what happens when you mix template driven and reactive forms?
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: stackoverflow.com/questions/39142616/…) 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.