Search code examples
angularangular-formsangular-reactive-formsdebouncing

Angular Reactive Forms: Debounce only some specific Form Control


I have a simple Search Component which contains a Reactive Form with 2 elements:

  • Text Input (to search for arbitrary matching text)
  • Checkbox (to include / exclude deleted results)

So far I use myFormGroup.valueChanges.subscribe(...) to execute my search method.

Now the problem is, that I want to debounce the text input. And at the same time not debounce the checkbox, so the search method is getting executed instantly when clicking the checkbox.

Using valueChanges.debounceTime(500) will of course debounce the whole form. That's not what I want.

This is a stripped down example. The real form has some more inputs. Some should be debounced and some shouldn't.

Is there any easy way to get this done? Or do I have to subscribe to every form control separately?

Would be nice to see how you did solve this.

Thanks in advance.


EDIT: Code

export class SearchComponent {

  myFormGroup: FormGroup;

  constructor(fb: FormBuilder) {
    this.myFormGroup = fb.group({
      textInput: '',
      checkbox: false
    });
  }

  ngOnInit() {
    this.myFormGroup.valueChanges.subscribe(val => {
      // debounce only the textInput,
      // and then execute search
    });
  }

}

Solution

  • Debounce the text control's valueChanges observable, then use combineLatest() to combine it with the checkbox control's valueChanges observable.

    Simple example