vala khosravi vala khosravi - 11 months ago 159
TypeScript Question

call keyup event with delay in angular

I have text box and assigned to it keyup event a search function but I want it to happens with delay not on every keypress

here is the html code :

<input type="text" [(ngModel)]="searchedKPI" (keyup)="searchConfigTree()">


and here is ts code :

list = list.filter(item => item.label.toLocaleLowerCase().includes(this.searchedKPI.toLocaleLowerCase())).slice();


and here is the example I wanted to search "text" string but event happens 4 time, I want to this happens once only for "text" string :

enter image description here

what the solution ?

Answer Source

Welcome to the Observable's world. Just use Observable to get the desired result. Get the reference of your input in the component and use this code. debounceTime will let the event to trigger at least after 1 second from the previous trigger. It will let you not to fire on every keyup when user types fast.

Observable.fromEvent(yourInput, 'keyup').debounceTime(1000).subscribe(value => /* */)

In the subscribe method you can write your logic. The value is the value of the input.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download