Angular 2 - Debouncing a keyUp event

23,999

Solution 1

UPDATE: Using RXJS 6 pipe operator:

this.subject.pipe(
  debounceTime(500)
).subscribe(searchTextValue => {
  this.handleSearch(searchTextValue);
});

You could create a rxjs/Subject and call .next() on keyup and subscribe to it with your desired debounceTime.

I'm not sure if it is the right way to do it but it works.

private subject: Subject<string> = new Subject();

ngOnInit() {
  this.subject.debounceTime(500).subscribe(searchTextValue => {
    this.handleSearch(searchTextValue);
  });
}

onKeyUp(searchTextValue: string){
  this.subject.next(searchTextValue);
}

HTML:

<input (keyup)="onKeyUp(searchText.value)">

Solution 2

An Update for Rx/JS 6. Using the Pipe Operator.

import { debounceTime } from 'rxjs/operators';

this.subject.pipe(
      debounceTime(500)
    ).subscribe(searchTextValue => {
      this.handleSearch(searchTextValue);
    });

Everything else is the same 👍

Solution 3

Take a look at answer here: https://stackoverflow.com/a/35992325/751200

And article here: https://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html (quite old, but still good).

Basically, you can use an Observable object provided by Angular Forms.

For example, this.myFormGroup.get("searchText").valueChanges.pipe(debounceTime(500), distinctUntilChanged()).subscribe(...)

If you need to perform an HTTP request when user stops typing, you can place such HTTP call into switchMap operator and add it to pipe list:

this.myFormGroup.get("searchText")
                .valueChanges
                .pipe(debounceTime(500),
                      distinctUntilChanged(), 
                      switchMap((value: string) => {
                          return this.service.getData(value);
                      }))
                .subscribe((valueFromRest) => { ... });

The magic in switchMap will automatically cancel the previous HTTP request (if it's not completed yet) and start a new one automatically.

Share:
23,999

Related videos on Youtube

Nicolas
Author by

Nicolas

Student Interactive multimedia design (IMD) at Thomas More, Belgium. Always trying to learn and improve. Curious person, open for a challenge.

Updated on July 09, 2022

Comments

  • Nicolas
    Nicolas almost 2 years

    How can I debounce a function which gets called on an "keyUp" event?

    Here is my code:

    My Function

    private handleSearch(searchTextValue: string, skip?: number): void {
        this.searchTextValue = searchTextValue;
        if (this.skip === 0 || typeof skip === "undefined") {
            this.skip = 0;
            this.pageIndex = 1;
        } else {
            this.skip = skip;
        }
        this.searchTextChanged.emit({ searchTextValue: searchTextValue, skip: this.skip, take: this.itemsPerPage });
    }
    

    My HTML

    <input type="text" class="form-control" placeholder="{{ 'searchquery' | translate }}" id="searchText" #searchText (keyup)="handleSearch(searchText.value)">
    

    Bassically what I'm trying to achieve is that handleSearch gets called a few moments after the user stop typing.

    I found out i can use lodash's _debounce() for this, but I haven't found out how to put this on my keyUp event.

  • Nicolas
    Nicolas about 7 years
    how can I pass parameters to ngOnInit() { this.subject.debounceTime(500).subscribe(res => { //do something }); }?
  • Ploppy
    Ploppy about 7 years
    You can pass your search query to onKeyUp() then pass it to the .next() and then it would be the 'res' variable in the subscription. Make sure to change the subject from Subject<any> to Subject<string> as you are working with a string. Let me edit the answer.
  • Nicolas
    Nicolas about 7 years
    and if I have 1 optional parameter? should i put them in an object? In the OP I rely on searchTextValue and skip which is optional
  • Ploppy
    Ploppy about 7 years
    I edited it again. About skip, just create a skip variable in your component and use it in the handleSearch method like this: if(this.skip)
  • Nicolas
    Nicolas about 7 years
    I missed something in your solution, so srry for the dumb questions about the parameters! It works!
  • Ploppy
    Ploppy about 7 years
    No problem, don't worry ;)
  • Téwa
    Téwa about 6 years
    Don't forget to import 'rxjs/add/operator/debounceTime'
  • reckface
    reckface about 6 years
    @Ploppy this is just so so beautiful T_T
  • Dan Chase
    Dan Chase over 2 years
    When I try this, I'm also getting a delay on the enter key as well, how to avoid? If they stop typing for 1 second, it's firing correctly, but if I hit enter, it's still taking 1 second to fire. I have (keyup)="keyUpFunction($event);" (enter.keyUp)="enterFunction(event)".. problem is enter is also firing generic keyup.