Angular 2 – Debouncing a keyUp event

Issue

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.

Solution

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)">

Answered By – Ploppy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published