Thuan Tran
Thuan Tran

Reputation: 329

debounceTime makes form control run twice

I'm using debounceTime to get a list in a dropdown, so far everything works just fine I typed three characters and it triggers api call return to me a list, but the problem is when I choose one item in the list the valueChanges of from Control causes this to call again, which is unnecessary. How to prevent this?

Here is my code:

this.myForm.controls['control'].valueChanges.pipe(
      filter(text => text.length > 2),
      debounceTime(1000),
      distinctUntilChanged()).subscribe((value: string) => {
        this.getItem(value);
});

Upvotes: 1

Views: 446

Answers (2)

Sameer Ahmed
Sameer Ahmed

Reputation: 190

if you are working on angular then you shouldn't use getElementById() instead use even keyup, keydown, blur to fire your method like:

<input type="text" id="inputText" (keyup)="fetchList()">

fetchList(){
distinctUntilChanged()).subscribe((value: string) => {
        this.getItem(value);
}

You can add debounce before calling your api

Upvotes: 0

coder
coder

Reputation: 8702

I think its better to give a Id for the form control that you are looking for text inputs like bellow:

<input type="text" id="inputText">

Then only use that form control to fetch the data when typing on it like bellow example:

  ngOnInit() {
    const inputText = document.getElementById('inputText');
    const typeahead = fromEvent(inputText, 'input').pipe(
      map((e: KeyboardEvent) => (<HTMLInputElement>e.target).value),
      filter(text => text.length > 2),
      debounceTime(10),
      distinctUntilChanged()
   );

    typeahead.subscribe(data => {
      this.getItem(data);
    });
  }

Then it will only fire when you are typing on that input form controller

Working DEMO

Upvotes: 1

Related Questions