0

I am developping a datalist facility. On keyup event of the input, I am calling a get request that send back an array of string which populate the datalist

<input type="text (keyup)="findPostalCode($event)" list="codePostalId" />
<datalist id="codePostalId">
    <option *ngFor="let code of postalCodeList">{{code}}</option>
</datalist>

Here is the component function that manages keyup event

 findPostalCode(event: any) {
    event.stopPropagation();
    event.preventDefault();
    this.postalCodeList = [];
    let text = event.target.value;
    if (text != null && text.length > 2) {
      this.produitImmobilierService.getPostalCodes(text).subscribe( result => {this.postalCodeList = result; });
    }
  }

And the keyup event trigger twice when I enter a character into the input.

flamant
  • 733
  • 4
  • 15
  • 41

2 Answers2

0

I can clearly see two events in you ts code. The first one is stopPropagation() and second one is preventDefault(). I am not sure why you coded like that but I would suggest you to wrap them in if condition so that events can happen based on certain condition.

siddpro
  • 81
  • 9
  • Hi, I did what you suggested, but I still have the issue of double trigger the keyup event when entering the input field – flamant Oct 25 '20 at 19:48
  • Could you please elaborate? Both those functions are JS implementation used basically to [prevent event bubbling and propagation](https://stackoverflow.com/a/5963688/6513921). I see only one event generation point here, the `keyup` binding. – ruth Oct 25 '20 at 20:04
  • I just use those event interruption in case the first keyup event propagate a new keyup event. It is just a cautious care. Untill now, I don't see what happen. It is just a try – flamant Oct 25 '20 at 21:04
  • I think i found the solution. To enter a digit I must keyup shift + digit, so 2 keyup. it was obvious – flamant Oct 27 '20 at 17:59
0

Try following code on your keyup.enter event of input.

<input type="text (keyup.enter)="$event.preventDefault();findPostalCode($event)" list="codePostalId" />

Hopefully, it will resolve your problem and event will be triggered only once.