Bbit
Bbit

Reputation: 442

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.

Upvotes: 4

Views: 13384

Answers (2)

Saksham
Saksham

Reputation: 9380

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.

Upvotes: 11

Pa Ri
Pa Ri

Reputation: 465

https://stackblitz.com/edit/angular-rwrinz-sxjtfj

  this.control.valueChanges
          .pipe(
            debounceTime(1000), // Waiting for 1 sec while you are typing
            distinctUntilChanged() // Prevents the emitting if the 'start' value and the 'end' value are the same
          )
          .subscribe(value => {
            console.log(value);
            // TODO: call BE here with this.httpClient...
          });

Don't forget to unsubscribe...

Upvotes: 4

Related Questions