Search code examples
angularinputtimerdelay

I want to trigger onChange after a delay from last change


Basically, I have an angular application, and I would like to have (change) only be triggered after a few seconds of nothing happening. Therefore instead of sending requests every time a letter is written in an input field, only after writing a letter and nothing happening for a few seconds, then the request would be sent.


Solution

  • You may use rxjs debounceTime piped to the valueChanges observable of the reactive FormControl as in the example at https://stackblitz.com/edit/angular-debounce-form-control

    The logic is to get the reference to your input using FormControl and subscribe to the valueChanges method and pipe a debounceTime to fire the callback method only if not fired in a specific interval.

    this.searchControl.valueChanges
    .pipe(
        debounceTime(2000),
        distinctUntilChanged()
    )
    .subscribe(res => {
        //your API call
    });
    

    Here distinctUntilChanged() makes the subscription callback execute only if a different value is emitted.