How can i detect only changed values in angular forms?

Viewed 1447

In angular forms, how can I detect only changed fields whose values are different than their initial values?

3 Answers

Use valueChanges to detect updates in form controls:

form:

this.myForm.valueChanges.subscribe(value => {
  console.log(value);
});

or specific control:

this.myForm.controls['controlName'].valueChanges.subscribe(value => {
  console.log(value);
});
import { Component } from '@angular/core';
import { FormGroup , FormBuilder} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form: FormGroup;
  initalFormValue: FormGroup;
  constructor(private formBuilder: FormBuilder){

  }
  ngOnInit() {
    this.form = this.formBuilder.group({
       ........
        });
      this.initalFormValue = this.form;
  }
}

You will save the initial form value in another form group and then you can able to compare each other

You will need to store the initial value

this.form = this.formBuilder.group({
  foo: ['bar'],
});

this.initialFormValue = this.form.value;

Later you can compare the value to this.initialFormValue


Edit:

You could install a valueChange Subscription on every form control (you could do that with a loop for each forms control), which uses the scan operator.

fooControl.valueChanges.pipe(
  scan((acc, curr) => { acc[1] = curr; return acc; }, [fooControl.value, fooControl.value]),
).subscripe(([initial, current]) => console.log("Has foo the initial value?", initial === current));
Related