21

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

}
Benjamin M
  • 23,599
  • 32
  • 121
  • 201
  • 1
    https://stackblitz.com/edit/angular-949zs3?file=app/app.component.ts – yurzui Mar 04 '18 at 09:40
  • Looks quite hacky, but seems to work. Another idea: Maybe there's some way to see which value inside the FormGroup changed? Then I could do something like `valueChangesDiff.debounce(diff => diff.textInput ? 500 : 0)` – Benjamin M Mar 04 '18 at 10:06

8 Answers8

36

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

import { debounceTime, distinctUntilChanged } from "rxjs/operators";

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.

Daniel Netzer
  • 2,151
  • 14
  • 22
7

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

Simple example

yurzui
  • 205,937
  • 32
  • 433
  • 399
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    My real form has 4 Text Inputs and lot's of Checkboxes and Selects. I don't want combineLatest with over 20 form controls. There must be another way. – Benjamin M Mar 04 '18 at 00:59
  • 5
    I'll quote myself: "This is a stripped down example. The real form has some more inputs. Some should be debounced and some shouldn't." – Benjamin M Mar 04 '18 at 08:35
  • Sorry, I missed that in the question. – JB Nizet Mar 04 '18 at 08:42
  • But thank you, I'll highlight this part of the question. – Benjamin M Mar 04 '18 at 08:44
  • I created a function that does exactly this, but in an easy way for lots of form controls: https://stackblitz.com/edit/angular-apryfv?file=app%2Fdebounce-form-values.ts – Manduro Apr 18 '18 at 11:50
6

Debounce for a single control in a form group can be done by

   this.form.get('textInput')
  .valueChanges
  .pipe(debounceTime(500))
  .subscribe(dataValue => {
    console.log("dataValue", dataValue);
  });
Shubham
  • 150
  • 1
  • 7
6

Right now I had that problem, I solved it as follows!

// Reactive control
fieldOne = this.formBuilder.control('');

// Reactive form
formGroup = this.formBuilder.group({
  fieldOne: [],
  fieldTwo: [],
  fieldX: [],
});

this.fieldOne.valueChanges
  .pipe(debounceTime(300))
  .subscribe(value => {
    this.formGroup.get('fieldOne').setValue(value);
  });

you have response speed in the controls within the form group and a delay in the events emitted from the individual control, hopefully in the future that the valueChanges emitted by the formGroup will present the control that triggered the event and be able to use filter in the observable

Regards!

Jesus Marquez
  • 76
  • 1
  • 1
2

You can use the following code that:

  • Uses startWith to emit an initial value, so any form changes immediately trigger an emission
  • Groups the current and previous values
  • Checks if the change is in a field we want to delay and if so, debounce by a set time
this.formGroup.valueChanges
.pipe(
     startWith(this.formGroup.value),
     pairwise(),
     debounce(([previous, current]) => previous.textInput !== current.textInput ? timer(500) : timer(0))
).subscribe(([_, current]) => this.usefullCallback(current));
user16217248
  • 3,119
  • 19
  • 19
  • 37
Sasha
  • 21
  • 2
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 18 '23 at 05:00
0

There's an issue on GitHub, which may(?!) solve this in the future:

https://github.com/angular/angular/issues/19705

Then it should be possible (like in AngularJS) to debounce single input fields.

Benjamin M
  • 23,599
  • 32
  • 121
  • 201
0

I faced the same issue and in my case creating a new Input component and providing debounce value in html solved issue without any custom code

Arti
  • 7,356
  • 12
  • 57
  • 122
0

You can get valueChanges on your formGroup and add a debounceTime (or debounce) only if a certain field change:

import { startWith } from 'rxjs/operators';
import { debounce, pairwise, timer } from 'rxjs';
...

this.formGroup
  .valueChanges
  .pipe(
    startWith(this.formGroup.value),
    pairWise(),
    debounce(([beforeValueChanges, afterValueChanges]) => 
        beforeValueChanges.search !== afterValueChanges.search 
        ? timer(500) 
        : timer(0)
    )
  ).subscribe(([unusedValue, afterValueChanges]) => {
    // .. Do what you want with afterValueChanges
  }

Explanations for the pipe:

  1. startWith() Get formGroup value, before valueChanges
  2. pairWise() Will create array with [beforeValueChanges, afterValueChanges]
  3. debounce() Check if textInput is different between before and after, so let put a debounce 500 if true.

Thanks to Sasha answer

Arthur Bouchard
  • 425
  • 6
  • 7