Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    });
  }

}
like image 203
Benjamin M Avatar asked Mar 04 '18 00:03

Benjamin M


People also ask

Which is better template driven or Reactive forms?

Template Driven Forms are based only on template directives, while Reactive forms are defined programmatically at the level of the component class. Reactive Forms are a better default choice for new applications, as they are more powerful and easier to use.

Are Reactive forms asynchronous?

The Reactive Forms Module in Angular allows you to add synchronous and asynchronous validators to form elements. Synchronous validators of a form element always run when a keyup event happens on that element.

What is FormBuilder in Reactive forms?

In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.


2 Answers

Create each individual FormControl before adding them to the form group and then you can control the valueChanges observable per FormControl

this.textInput.valueChanges
      .pipe(
        debounceTime(400),
        distinctUntilChanged()
      )
      .subscribe(res=> {
        console.log(`debounced text input value ${res}`);
      });

the distinctUntilChanged will make sure only when the value is diffrent to emit something.

like image 130
Daniel Netzer Avatar answered Sep 17 '22 14:09

Daniel Netzer


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

Simple example

like image 20
JB Nizet Avatar answered Sep 18 '22 14:09

JB Nizet