Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 how to use debouncetime for input change event (keyup)

How to use debounce time for searching data in API's for keyup input change event. Give a look at the following code. It is not working. A search request to API is made on every input change. I want to make a search request to API using some denounce time.

Thank you in advance

.html

 <input matInput (keyup) ="Onsearchinput($event.target.value)">

.ts

Onsearchinput(value){

    debounceTime(500)

    console.log(value)

      this.productService.search_Products(value).subscribe(data => {
        if(data){
          console.log(data)
          this.product_list = data
        }
      })
  }
like image 970
pratik jaiswal Avatar asked Oct 14 '25 04:10

pratik jaiswal


1 Answers

A form control will expose the changes in its values as an observable named valueChanges. You're going to need to use the pipe operator, piping valueChanges into it. You can't just call debounceTime like you are doing above.

You're also going to want to use something like a switchMap to ensure that any in-flight requests are cancelled if a user types something while a request is in progress.

Without seeing your code this is the best I can really do.

Try using a formControl.

html;

<input matInput [formControl]='myControl'>

In your ts, declare this as a class variable:

myControl = new FormControl();

Then pipe the changes from it like this (can go in ngOnInit):

this.myControl.valueChanges.pipe(
   debounceTime(500),
   switchMap(changedValue => this.productService.search_Products(changedValue)),
).subscribe(productList => this.product_list = productList);
like image 191
deaks Avatar answered Oct 16 '25 17:10

deaks