2

I am working on the reactive forms and I am not able to get the specifically the form control which has changed or updated from UI rather getting the whole form . I tried using valueChanges() but it returns the full form itself rather than giving me the specific changed form control .

I tried using the valueChanges() method but no getting what i am expecting

1
  • did you check the answers , are they work ? for you it's will be great if you provide any feedback🤔🤔 Commented Apr 27, 2019 at 4:13

2 Answers 2

3

You can subscribe to specific form control rather than the entier form lie this way

this.form.get('userName').valueChanges(value=> console.log('name change',value))

you can manage subscribe to form controls dynamically like this

this.form = fb.group({
  name: [],
  age: [],
  address: [],
});

Object.keys(this.form.controls).forEach(key  => {
  this.form.get(key).valueChanges.subscribe(value =>{
    console.log(`control ${key} has change =>` ,value)
  })
});

stackblitz demo 🚀🚀

1
  • HI Malbarmawi , thank you for replying . I was aware that we have to loop over the keys and check if the form control has changed. But i was looking for any particular method of reactive forms , which could only give the changed control as soon there is some change instead of looping and checking for each form control . Thanks again for the answer Commented Apr 27, 2019 at 17:29
1

you can still use form valueChanges pipe with pairwise operator to get the previous and current value and by compare both values you can get the the controls that changes

constructor(private fb: FormBuilder) {
    this.form = fb.group({
      name: [],
      age: [],
      address: [],
    });

    this.form.valueChanges.
       pipe(debounceTime(2000) ,startWith(null), pairwise()).  
       subscribe(([prev, next]) => {
        if (prev === null) { // 👈 run only first time 
          console.log(this.getValue(next))
        } else { // 🚨 compare values
          const result = {};
          const keys = Object.keys(next);

          keys.forEach(key => {
            if (prev[key] !== next[key]) {
              result[key] = next[key]
            }
          });
          console.log(result) ; // 🔵 the value that has changed 
        }
      })
  }

  // 👇👇 
  // for the first time all form controls are null 
  // so this mwthos get the value of object taht has a value 
  getValue(obj) {
    return Object.keys(obj).reduce((prev: any, key) => {
      if (obj[key]) {
        prev[key] = obj[key];
      };
      return prev;
    }, {})
  } 

stackblitz demo 🔥🔥

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.