Angular 4 Keyup event fire multipletime?

i'll explain more of what i've learned answering this stackoverflow question.

well, lets just start by explaining that if you want say some AutoComplete based on an input element, so the problem with Keyup event is that while user is typing "Angu" you actually get 4 events, 1st with input value as "A", 2nd "An", ect.

but you want the part where he did "Angu" ...

well, there is the native answer, and the RxJs Implementation for that, and i will just start with the RxJx code for the reference, and then go for my Native Javascript example.

as you can see youself in my plnkr, we import the Observable as an object and then adding relevant Observable type and operator.

couple or sources to that:
some recipes medium.com 
from the RxJs site reactivex.io

anyways these are the imports
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/auditTime';

and this is the code
@ViewChild('inputbox') private inputbox : ElementRef; 
  
ngAfterViewInit(){
  Observable.fromEvent(
    this.inputbox.nativeElement, 'keyup')
    .auditTime(500)
    .subscribe(()=>{ this.loadDataApiCall(); });  
}

now lets me just explain what i've done with native js just to get the point just like my plnk here

well, some basis, what is
@ViewChild('ta')   private ta : ElementRef; 

well, in angular you can reference an element in your template with @ViewChild and select elements there with all kinds of rules and do magnificent things with it, read in angular and alligator.

this is just for the example output.

whenever you have a keyup event you need to register it for future process, this future needs to be long enough for the user to type more characters and fast enough to get your data so the user wont go away or feel its broken.

you also need to send the data with the registry to keep checking it vs. the current value, until its not changed anymore.

notice that i used bind(this) with the setTimeout in order that the this inside the called function in setTimeout will be our component.

Enjoy!

Comments

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

SOLVED The item could not be indexed successfully because the item failed in the indexing subsystem

Asp.Net Ending Response options, Response.End() vs CompleteRequest()