I want to trigger onChange after a delay from last change

给你一囗甜甜゛ 提交于 2021-02-08 10:01:54

问题


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.


回答1:


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.




回答2:


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...



来源:https://stackoverflow.com/questions/57123123/i-want-to-trigger-onchange-after-a-delay-from-last-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!