Utilize the valueChanges
pipe along with the pairwise
operator to access both the previous and current values. By comparing these values, you can identify which controls have changed.
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 method gets the value of objects that have a value
getValue(obj) {
return Object.keys(obj).reduce((prev: any, key) => {
if (obj[key]) {
prev[key] = obj[key];
};
return prev;
}, {})
}
Check out the stackblitz demo 🔥🔥