Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: on form change event

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?

like image 734
BeRightBack Avatar asked Jun 30 '26 22:06

BeRightBack


2 Answers

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]) => ... );
like image 104
Muhammad Kamran Avatar answered Jul 02 '26 10:07

Muhammad Kamran


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.

like image 29
AT82 Avatar answered Jul 02 '26 12:07

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!