I have form group in my angular app. Since I would like to aviod writing onChange for each form element, my idea was to subscribe to entire form changes, and then on event check changed element
So this is relevant part of the code:
constructor(){
this.orderForm = this.formBuilder.group({
...
});
this.event$ = this.orderForm.valueChanges.subscribe((x:any) => {
console.log('form value changed')
console.log(x)
});
Problem is, this x is just entire form so I have no idea what element is changed
Is there any smart way to find out what form element changed?
I don't thing there is a function that returns only the formControls that have changed.
But since valueChanges is an observeable you could use pairwise to get the previous and the next value. And compare them to find out what has changed.
this.orderForm.valueChanges
.pipe(startWith(null), pairwise())
.subscribe(([prev, next]: [any, any]) => ... );
This works well if you have a simple form with just formcontrols, no nested groups or FormArrays.
You can use rxjs merge for each form controls value changes and figure out which one changed:
merge(
...Object.keys(this.orderForm.controls).map(
(controlName: string) =>
this.orderForm.get(controlName).valueChanges.pipe(
tap((value) => {
console.log(`Control "${controlName}" changed. New value: ${value}`)
})
)
)
).subscribe();
Here's a STACKBLITZ for your reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With