I'm trying to build an Angular reactive form in which inputs field values are updated based on inputs in other fields. Three input fields amount, price and total are supposed to reflect changes so that amount * price = total holds. Full code https://stackblitz.com/edit/angular-e7rnxf
import {
Component,
Input
} from '@angular/core';
import {
FormBuilder
} from '@angular/forms';
@Component({
selector: 'hello',
template: `
<form [formGroup]="orderForm" (ngSubmit)="onSubmit()">
Amount: <input (keyup)="onAmountChange($event)" formControlName="amount">{{ orderForm.value.amount }}<br>
Price: <input (keyup)="onPriceChange($event)" formControlName="price">{{ orderForm.value.price }}<br>
Total: <input (keyup)="onTotalChange($event)" formControlName="total"> {{ orderForm.value.total }}<br>
<button type="submit">Submit</button>
</form>
`
})
export class HelloComponent {
constructor(private fb: FormBuilder) {}
orderForm = this.fb.group({
amount: 200,
price: 95,
total: ''
});
onTotalChange(e) {
const total = e.currentTarget.value;
this.orderForm.value.amount = total / this.orderForm.value.price;
}
onAmountChange(e) {
const amount = e.currentTarget.value;
this.orderForm.value.total = this.orderForm.value.amount * this.orderForm.value.price;
}
onPriceChange(e) {
const price = e.currentTarget.value;
this.orderForm.value.total = price * this.orderForm.value.amount;
}
onSubmit() {
console.log(this.orderForm.value);
}
}
(keyup)s, simply subscribe tothis.orderForm.valueChanges. It's a good idea to read at least the documentation's first page